title: How to get an object of a unknown class with given classname
body: <p>I am searching for a way to determine at runtime, which type of object should be alloced (based on a given class name, which is of type <code>const char*</code>).</p>
  
  <p>Well the simplest way of course is to use loads of <code>if</code>s /<code>else if</code>s, but that doesnt seem applicable, because i have > 100 different classes(well at least they all derive from one base class), and i have to add new classes quite regularly aswell.</p>
  
  <p>I already came up with a first draft, but sadly it doesnt compile yet (mingw &amp; g++ 4.4)</p>
  
  <pre><code>template&lt;typename TBase, typename TDerived, typename... TArgs&gt;
  Base* get_classobject(const char* classname)
  {
      if(strcmp(classname,typeid(TDerived).name())==0)
          return new TDerived; //
      else if(sizeof...(TArgs)&gt;0)
          return get_classobject&lt;TBase,TArgs...&gt;(classname);
      else
          return 0;
  }
  
  
  int main()
  {
      Base* obj = get_classobject&lt;Base,A,Foo,B,C&gt;("Foo");
      // ^- Types A B C and Foo are all derived from Base
      delete obj; //of course we got an virtual dtor ;)
      return 0;
  }
  </code></pre>
  
  <p>but that <code>sizeof...(TArgs)&gt;0</code> doesnt stop gcc from trying to generate code for <code>get_classobject&lt;TBase,const char*&gt;(const char*)</code> which fails</p>
  
  <p>Do you have any idea, how to fix this, or any other idea ?
  Thanks.</p>
  
  <p>EDIT: i solved it:</p>
  
  <pre><code>template&lt;typename TBase, typename TDerived&gt;
  Base* get_classobject(const char* classname)
  {
      if(strcmp(classname,typeid(TDerived).name())==0)
          return new TDerived;
      return 0;
  }
  
  template&lt;typename TBase, typename TDerived, typename TArg, typename... TArgs&gt;
  Base* get_classobject(const char* classname)
  {
      if(strcmp(classname,typeid(TDerived).name())==0)
          return new TDerived;
      return get_classobject&lt;TBase,TArg,TArgs...&gt;(classname);
  }
  </code></pre>
  
  <p>EDIT For interested readers:<br/>
  You should now that the implementation above is NOT compiler independent at all.
  The output of <code>typeif(sometype).name()</code> is compiler/implementation specific.
  Using a <code>static const char* name</code> variable or function inside all Derived classes, would fix this, but adds a bunch of work(of course you can use a macro for this, but if you are using macros already, you could aswell use another object factory method)</p>