fork download
  1. #include <cstdio>
  2. #include <cstdarg>
  3. #include <functional>
  4.  
  5. class PrintWrapper
  6. {
  7.  
  8. public:
  9. PrintWrapper() = default;
  10.  
  11.  
  12. template<typename T>
  13. PrintWrapper( T&& t) : func(std::forward<T>(t))
  14. {
  15.  
  16. }
  17.  
  18.  
  19. int operator()(char const* format, ...)
  20. {
  21. va_list args;
  22. va_start(args, format);
  23. int result = func(format, args);
  24. va_end(args);
  25. return result;
  26. }
  27. private:
  28.  
  29. std::function< int(char const*, va_list)> func;
  30.  
  31. };
  32.  
  33. int main()
  34. {
  35. // Note, you have to use the 'v' versions
  36. PrintWrapper p = std::vprintf;
  37. p("%d %d %s\n", 1,2, "hello");
  38. char buffer[256];
  39. using namespace std::placeholders;
  40. p = std::bind(std::vsnprintf, buffer, sizeof(buffer), _1, _2 );
  41.  
  42. p("%lf %s\n", 0.1234, "goodbye");
  43.  
  44. // Since the previous step was a wrapper around snprintf, we need to print
  45. // the buffer it wrote into
  46. printf("%s\n", buffer);
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
1 2 hello
0.123400 goodbye