title: Storing a c++ struct of unknown type in a void pointer - What struct property is required?
body: <p>I want to use my function <code>assign</code> below, to store a struct of unknown type at a specific memory address stored in a void pointer. This works fine for some structs (e.g. with <code>Test1</code>), but for other structs it does not work (e.g. with <code>Test2</code>). Unfortunately, I could not find any pattern for what sort of structs it will work, as it has worked for some POD and non-POD structs.</p>
  
  <p>What criteria must be fulfilled for a struct in order to store it this way?</p>
  
  <pre><code>#include &lt;vector&gt;
  
  template &lt;typename T&gt;
  void assign(void* p, T obj){
      T* t = reinterpret_cast&lt;T*&gt;(p);
      *t = obj;
  }
  
  struct Test1{
      int i1;
      int i2;
  };
  
  struct Test2{
      std::vector&lt;int&gt; i;
  };
  
  int main()
  {
      void* p = new char[100];
      Test1 test1;
      test1.i1 = 0;
      test1.i2 = 0;
      Test2 test2;
      test2.i = std::vector&lt;int&gt;();
  
      assign(p, test1);
      assign(p, test2);
  
      delete[] p;
      return 0;
  }
  </code></pre>
  
  <p><strong>Edit:</strong></p>
  
  <p>Why do I want to have this? I am currently implementing a game engine that uses an entity-component-system model (An entity is a game object, a component is kind of its attribute(s) and a system implements the logic to modify components.). There is a class that stores and manages entities (not surprisingly called <code>EntityManager</code>). Some programmer that uses my engine can define components (simply structs, only meant to contain data and no functionality) for an entity. The <code>EntityManager</code> therefore needs to store objects whose type is not known beforehand. A further restriction is that the components should be stored in an efficient way, i.e. behind each other in memory. This is the reason why a simple approach like having a base class <code>Component</code> and then having a member variable <code>vector&lt;vector&lt;Component*&gt;&gt;</code> is not appropriate.</p>
  
  <p>My solution is that the <code>EntityManager</code> allocates enough space to store a certain user-defined maximal number of entities beforehand. A given component can then be stored with the <code>assign</code> function above.</p>