title: C++ Generic way to provide `operator<<` for middleware generated types
body: <p>We use a middleware that generates types for us for various programming languages, including C++. For structures generated for C++ I want to inject code that can be used for various data conversion, for example output to <code>std::ostream</code>. Let's say we have following structure generated:</p>
  
  <pre><code>struct Foo {
      int a;
      double d;
  };
  </code></pre>
  
  <p>Let's say I change middleware compiler to produce following template function:</p>
  
  <pre><code>template&lt;typename Visitor&gt;
  void visit( Visitor &amp;v, const Foo &amp;data )
  {
      v.visit( "a", data.a );
      v.visit( "d", data.d );
  }
  </code></pre>
  
  <p>now I can use this code for various ways and it should not affect anything if not used, for example make <code>std::ostream::operator&lt;&lt;</code>:</p>
  
  <pre><code>struct OstreamVisitor {
      OstreamVisitor( std::ostream &amp;os ) : m_os( os ) {}
  
      void visit( const char *name, int i ) { m_os &lt;&lt; name &lt;&lt; "=" &lt;&lt; i &lt;&lt; std::endl; }
      void visit( const char *name, double d ) { m_os &lt;&lt; name &lt;&lt; "=" &lt;&lt; d &lt;&lt; std::endl; }
  
      std::ostream &amp;m_os;
  };
  
  std::ostream &amp;operator&lt;&lt;( std::ostream &amp;out, const Foo &amp;data )
  {
      OstreamVisitor v( out );
      visit( v, data );
      return out;
  }
  </code></pre>
  
  <p>it works <a href="https://ideone.com/GiSpso" rel="nofollow noreferrer">live example</a> but problem is I do not want to write <code>std::ostream &amp;operator&lt;&lt;</code> for every structure manually so naive solution would be to write:</p>
  
  <pre><code>template&lt;typename T&gt;
  std::ostream &amp;operator&lt;&lt;( std::ostream &amp;os, const T &amp;t );
  </code></pre>
  
  <p>and use visitor, but that would interfere with other types, that not generated. So is there way to make such generic function that limited only for structures, that generated? I would like not to inject anything to generated structures if possible but having template class instead of template function is fine.</p>
  
  <p>Note: I cannot restrict generated structs to belong to particular namespace unfortunately. What I am thinking is something like:</p>
  
  <pre><code>// system header
  template&lt;typename T&gt;
  struct visitable_tag;
  
  // generated header
  namespace FooNamespace {
  struct Foo { ... };
  
  template&lt;&gt;
  struct visitable_tag&lt;Foo&gt; {};
  }
  
   // or maybe have tag in special namespace
   namespace visitable_tag_namespace {
   template&lt;&gt;
   struct visitable_tag&lt;FooNamespace::Foo&gt; {};
   }
  </code></pre>
  
  <p>and then make template output function only instantiate when such specialization exits. Of course this is just idea of possible tagging and I open to other ways, but would prefer to have original structures untouched.      </p>