fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. struct Foo {
  5. int a = 1;
  6. double d = 2;
  7. };
  8.  
  9. template<typename Visitor>
  10. void visit( Visitor &v, const Foo &data )
  11. {
  12. v.visit( "a", data.a );
  13. v.visit( "d", data.d );
  14. }
  15.  
  16. struct OstreamVisitor {
  17. OstreamVisitor( std::ostream &os ) : m_os( os ) {}
  18.  
  19. void visit( const char *name, int i ) { m_os << name << "=" << i << std::endl; }
  20. void visit( const char *name, double d ) { m_os << name << "=" << d << std::endl; }
  21.  
  22. std::ostream &m_os;
  23. };
  24.  
  25. std::ostream &operator<<( std::ostream &out, const Foo &data )
  26. {
  27. OstreamVisitor v( out );
  28. visit( v, data );
  29. return out;
  30. }
  31.  
  32. int main()
  33. {
  34. Foo f;
  35. std::cout << f;
  36.  
  37. }
  38.  
Success #stdin #stdout 0s 4472KB
stdin
Standard input is empty
stdout
a=1
d=2