title: Best practice for passing primitive data type in C++ function
body: <p>I'm writing a function for an avr chip to deserialize a byte stream to primitive types. I'd like to do it in as generic a way as possible and was wondering what the best practice would be to determine the type to deserialize. Ideas I have so far, include:</p>
  
  <p>Choice A:</p>
  
  <pre><code>// Just write a function for each type
  double deserialize_double(uint8_t *in) { }
  </code></pre>
  
  <p>Choice B:</p>
  
  <pre><code>// Use a template, and pass the type in when calling
  // Function:
  template &lt;typename TYPE&gt;
  TYPE deserialize(uint8_t *in) {
    union {
      TYPE real;
      uint8_t base[sizeof(TYPE)];
    } u;
  
    for (unsigned int i = 0; i &lt; sizeof(TYPE); i++) {
      u.base[i] = in[i];
    }
    return u.real;
  }
  
  // Call:
  double value = deserialize&lt;double&gt;(in);
  </code></pre>
  
  <p>Choice C:</p>
  
  <pre><code>// Similar to B, but you pass in the type as a parameter
  // Function:
  TYPE deserialize(uint8_t *in, TYPE);
  
  // Call:
  double value = deserialize(in, double);
  </code></pre>
  
  <p>Choice D:</p>
  
  <pre><code>// Use a templated class. My main issue with this is I was hoping 
  // to re-use the same object for deserializing multiple types.
  template &lt;typename TYPE&gt;
  class Serializer {
    public void serialize(uint8_t *out, TYPE value) { /* code */ }
    public TYPE deserialize(uint8_t *int) { /* code */ }
  };
  </code></pre>
  
  <p>Any ideas on the best way to do this? Perhaps an easier method I overlooked.</p>