title: C++ Stream serialization
body: <p>Currently I'm trying to implement some kind of object stream, similar to the structure that exists in java.</p>
  
  <p>Using the <a href="http://www.pcs.cnu.edu/~dgame/sockets/socketsC++/sockets.html" rel="nofollow">"Stream Socket API" by Rob Tougher</a> it's easy to use the stream insertion <code>operator&lt;&lt;</code>.</p>
  
  <p>This would lead to the problem that every serializable object would require every single class to overload the same operators in the same manner.</p>
  
  <p>Example:</p>
  
  <pre><code>class A
  {
      protected:
          int value;
  
      friend ostream&amp; operator &lt;&lt;( ostream&amp; in, const A&amp; obj );
  };
  
  class B
  {
      protected:
          float value;
  
      friend ostream&amp; operator &lt;&lt;( ostream&amp; in, const B&amp; obj );
  };
  
  ofstream&amp; operator&lt;&lt; (ofstream&amp; in, const A&amp; obj)
  {
      return (in &lt;&lt; obj.value);
  }
  
  ofstream&amp; operator&lt;&lt; (ofstream&amp; in, const B&amp; obj)
  {
      return (in &lt;&lt; obj.value);
  }
  </code></pre>
  
  <p>Well. That's easy and works. Now I'm thinking about whether it's somehow possible to ease and automate the process of this serialization.</p>
  
  <p>I already thought back and forth how this could be done using some combination with both, templates and macros. Using <code>typeid</code> (RTTI) would partially work, but this fails at the point where you would need to cast a value in a type when only the typeid is known. Which simply isn't possible.</p>
  
  <p>Is there really no other solution that to simply let the user implement each and every <code>operator&lt;&lt;</code> ? Am I thinking too far and the solution is quite easy?</p>
  
  <p>Otherwise, in all ways I've tried and thought through, the problem ends at where I need to reinstanciate an object when the classname isn't known at compile-time.</p>
  
  <p>Any idea is appreciated.</p>
  
  <p>PS: Using <code>fwrite(item, sizeof(item), 1, handle);</code> isn't the solution as well. Not platform independent at all.</p>