title: Generic container for single type and single element in C++
body: <p>I need a container/wrapper C++ class which holds a single, arbitrary value. Once this value is set only values of the same type should be accepted.</p>
  
  <p>This is the code I've been experimenting with. </p>
  
  <pre><code>struct Genome {
  
  struct FitnessConcept {};
  
  template&lt;typename T&gt;
  struct Fitness : public FitnessConcept{
      T value;        
      Fitness(T value) : value(value){}
  };
  
  std::shared_ptr&lt;FitnessConcept&gt; fitness;
  
  template&lt;typename T&gt; 
  void setFitness(T value) {
      fitness.reset(new Fitness&lt;T&gt;(value));               
  }
  
  template&lt;typename T&gt;
  T getFitness() {
      return static_cast&lt;Fitness&lt;T&gt;*&gt;(fitness.get())-&gt;value;
  }           
  };
  </code></pre>
  
  <p>While <code>Genome</code> can hold arbitrary values, it does not restrict the type once the first is set, i.e. the following code is valid:</p>
  
  <pre><code>Genome g;
  g.setFitness(0.2);
  g.setFitness("foo"); //this should fail
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Both compile and runtime failures are ok.</p>