title: serialize any data type as vector<uint8_t> - use reinterpret_cast?
body: <p>I didnt find anything directly related in searching, so please forgive if this is a duplicate.</p>
  
  <p>What I am looking to do is serialize data across a network connection. My approach is to convert everything I need to transfer to a <code>std::vector&lt; uint8_t &gt;</code> and on the receiving side unpack the data into the appropriate variables. My approach looks like this:</p>
  
  <pre><code>template &lt;typename T&gt;
  inline void pack (std::vector&lt; uint8_t &gt;&amp; dst, T&amp; data) {
      uint8_t * src = static_cast &lt; uint8_t* &gt;(static_cast &lt; void * &gt;(&amp;data));
      dst.insert (dst.end (), src, src + sizeof (T));
  }   
  
  template &lt;typename T&gt;
  inline void unpack (vector &lt;uint8_t &gt;&amp; src, int index, T&amp; data) {
      copy (&amp;src[index], &amp;src[index + sizeof (T)], &amp;data);
  }
  </code></pre>
  
  <p>Which I'm using like</p>
  
  <pre><code>vector&lt; uint8_t &gt; buffer;
  uint32_t foo = 103, bar = 443;
  pack (buff, foo);
  pack (buff, bar);
  
  // And on the receive side
  uint32_t a = 0, b = 0;
  size_t offset = 0;
  unpack (buffer, offset, a);
  offset += sizeof (a);
  unpack (buffer, offset, b);
  </code></pre>
  
  <p>My concern is the </p>
  
  <p><code>uint8_t * src = static_cast &lt; uint8_t* &gt;(static_cast &lt; void * &gt;(&amp;data));</code> </p>
  
  <p>line (which I understand to do the same as <code>reinterpret_cast</code>). Is there a better way to accomplish this without the double cast?</p>
  
  <p>My naive approach was to just use <code>static_cast&lt; uint8_t* &gt;(&amp;data)</code> which failed. I've <a href="https://stackoverflow.com/questions/2158928/inherit-from-two-polymorphic-classes">been told in the past</a> that <code>reinterpret_cast</code> is bad. So I'd like to avoid it (or the construct I have currently) if possible.</p>
  
  <p>Of course, there is always <code>uint8_t * src = (uint8_t *)(&amp;data)</code>.</p>
  
  <p>Suggestions?</p>