title: How to associate object with its type
body: <p>I'm trying to create a statistics system in C++ which will allow me to associate a string with a value of an arbitrary type. Currently, I have it working with an <code>enum</code> that keeps track of the type and a <code>void *</code> that points to the object, but this requires me to make individual <code>if</code> statements for all of the types I want to support. I'd like to have it so that I can support any arbitrary type using some kind of template. I've created some test code that sort of works, but there are issues:</p>
  
  <pre><code>class Test {
      std::type_index type;
      void *value;
  
  public:
      template &lt;typename T&gt;
      Test(T val) : type(typeid(val)) {
          T *val_p = new T;
          *val_p = val;
          value = (void *)val;
      }
  
      Test() : type(typeid(void)) {
          value = nullptr;
      }
  
      ~Test() {
          //no idea how I could make this work
      }
  
      template &lt;typename T&gt;
      T get() {
          if (std::type_index(typeid(T)) == type) {
              T *val_p = (T *)value;
              return *val_p;
          } else {
              throw std::bad_typeid();
          }
      }
  };
  </code></pre>
  
  <p>What I have so far works, but I don't think it would be possible to implement a destructor or copy/move constructors. The whole point is I want to store this all in a single <code>std::unordered_map</code>, so I can't (AFAIK) just make a template class and go from there. So, is it possible to do what I'm trying to do, and if so, how would I do it?</p>