fork download
  1. #include <iostream>
  2.  
  3. //
  4. // Shim interface
  5. //
  6. struct Interface {
  7. virtual void print(std::ostream& out) const = 0;
  8. }; // struct Interface
  9.  
  10. std::ostream& operator<<(std::ostream& out, Interface const& i) {
  11. i.print(out);
  12. return out;
  13. }
  14.  
  15. template <typename T>
  16. struct IT: public Interface {
  17. IT(T const& t): _t(t) {}
  18. virtual void print(std::ostream& out) const { out << _t; }
  19. T const& _t;
  20. };
  21.  
  22. template <typename T>
  23. IT<T> shim(T const& t) { return IT<T>(t); }
  24.  
  25. //
  26. // printf (or it could be!)
  27. //
  28. void printf_impl(char const*, std::initializer_list<Interface const*> array) {
  29. typedef std::initializer_list<Interface const*>::const_iterator It;
  30. for (It it = array.begin(), end = array.end(); it != end; ++it) { std::cout << **it; }
  31. std::cout << "\n";
  32. }
  33.  
  34. template <typename... T>
  35. void printf_bridge(char const* format, T const&... t) {
  36. printf_impl(format, {(&t)...});
  37. }
  38.  
  39. template <typename... T>
  40. void printf(char const* format, T const&... t) {
  41. printf_bridge(format, ((Interface const&)shim(t))...);
  42. }
  43.  
  44. //
  45. // Usage
  46. //
  47. struct Pair { int first; int second; };
  48. std::ostream& operator<<(std::ostream& out, Pair const& p) {
  49. return out << "(" << p.first << ", " << p.second << ")";
  50. }
  51.  
  52. int main() {
  53. Pair const p = { 1, 2 };
  54. printf("unused", 1, 4, p);
  55. }
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
14(1, 2)