title: C++ overload << operator for class object acting as stream
body: <p>So I've browsed a bunch of other threads, but none pertain to the questions I have on this exact topic.  I am writing a C++ library to do socket communication. I have a TCP socket class which handles all operations on a TCP socket (setup, read/write, etc). I want to be able to read and write data to/from a TCP socket object using the &lt;&lt; and >> operators. For example, I want to be able to write, say, a double to the socket in this fashion:</p>
  
  <pre><code>double x;
  TcpSocket *sock = new TcpSocket();
  
  //socket setup stuff here...
  
  sock &lt;&lt; x;
  </code></pre>
  
  <p>At the moment, I have two templated overloaded operator functions within the TcpSocket class:</p>
  
  <pre><code>template&lt;typename T&gt;
  TcpSocket operator&lt;&lt;(TcpSocket sock, T &amp;val)
  {
      unsigned char bytesOfVal[] = //parse bytes of val here...
  
      sock.Write(bytesOfVal, sizeof(bytesOfVal));
  }
  </code></pre>
  
  <p>-</p>
  
  <pre><code>template&lt;typename T&gt;
  TcpSocket operator&gt;&gt;(TcpSocket sock, T &amp;val)
  {
      std::stringstream ss;
      byte buf[sizeof(val)];
  
      sock.Read(buf, sizeof(buf));
      ss.str(std::string(buf));
  
      ss &gt;&gt; val;
  }
  </code></pre>
  
  <p>where sock.Read( ) and sock.Write( ) issue the system calls read( ) and write( ) using a socket file descriptor (not really relevant but just FYI). These functions are templated in an attempt to be able to get the bytes for almost any data type in one place.</p>
  
  <p>So my questions are:</p>
  
  <ul>
  <li>Will these overloaded operator functions work in the way I want them to?</li>
  <li><p>If it works, can I chain these together, such as:</p>
  
  <p>sock &lt;&lt; 45.8 &lt;&lt; 33.9 &lt;&lt; "numbers";</p></li>
  </ul>
  
  <p>=========================================================================
  Here are my updated operator functions:</p>
  
  <pre><code>//Write to socket
  template&lt;typename T&gt;
  TcpSocket&amp; operator&lt;&lt;(TcpSocket&amp; sock, T &amp;val)
  {
      size_t buflen = sizeof(val);
      unsigned char buf[buflen];
  
      memcpy(buf, &amp;val, buflen);
  
      sock.Write(buf, buflen);
  
      return sock;
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>//Read from socket
  template&lt;typename T&gt;
  TcpSocket&amp; operator&gt;&gt;(TcpSocket &amp;sock, T &amp;val)
  {
      size_t buflen = sizeof(val);
      unsigned char buf[buflen];
      int numBytesRead = 0;
  
      numBytesRead = sock.Read(buf, buflen);
  
      memcpy(&amp;val, buf, numBytesRead);
  
      return sock;
  } 
  </code></pre>