title: How do I store and access a type dynamically in c++?
body: <p>I'm aware of c++ templates, which allow you to write code for multiple types, but what if I want to store and access a type dynamically? Why is this so difficult to do in c++?</p>
  <p>I would very much prefer to <strong>not</strong> have to do something like this:</p>
  <pre><code>enum SupportedTypes
  {
      IntType,
      FloatType,
      StringType
  }
  
  template &lt;typename T&gt;
  class ClassThing
  {
      public:
          T Value;
          SupportedTypes Type;
  }
  
  ...
  
  //Not sure if you could even access thing-&gt;Type, but regardless, you get the idea...
  switch (thing-&gt;Type)
  {
      case IntType:
          DoSomething(((ClassThing&lt;int&gt;*)thing)-&gt;T);
          break;
      case FloatType:
          DoSomething(((ClassThing&lt;float&gt;*)thing)-&gt;T);
          break;
      case StringType:
          DoSomething(((ClassThing&lt;string&gt;*)thing)-&gt;T);
          break;
  }
  </code></pre>
  <p>Why doesn't c++ support something like this:</p>
  <pre><code>int whatIsThis = 5;
  type t = typeid(whatIsThis); //typeid exists, but you can't do...:
  t anotherInt = 5;
  </code></pre>
  <p>?</p>
  <p>Another question that I have that I'm more optimistic of receiving a good answer to: if you choose to go the templated route, is there any way to maintain the type if you store it generically in a collection? E.g.:</p>
  <pre><code>vector&lt;ClassThing&gt; things;
  </code></pre>
  <p>(This will give an &quot;argument list for class template ... is missing&quot; error, by the way.) My guess is that no, this is not possible because the above is not possible.</p>