I am looking for a way to determine at runtime which type of object should be allocated (based on the given name of the class having the type const char*).
Well, the easiest way is to use if/ else ifs loads , but that doesn't seem to be applicable, because I have> 100 different classes (well, at least they all come from the same base class) and I should also add new classes pretty regularly .
I already came up with the first draft, but unfortunately it is not compiling yet (mingw and g ++ 4.4)
template<typename TBase, typename TDerived, typename... TArgs>
Base* get_classobject(const char* classname)
{
if(strcmp(classname,typeid(TDerived).name())==0)
return new TDerived;
else if(sizeof...(TArgs)>0)
return get_classobject<TBase,TArgs...>(classname);
else
return 0;
}
int main()
{
Base* obj = get_classobject<Base,A,Foo,B,C>("Foo");
delete obj;
return 0;
}
but sizeof...(TArgs)>0does not stop gcc from trying to generate code for get_classobject<TBase,const char*>(const char*)that that fails
Do you have any idea how to fix this or any other idea? Thank.
EDIT: I decided:
template<typename TBase, typename TDerived>
Base* get_classobject(const char* classname)
{
if(strcmp(classname,typeid(TDerived).name())==0)
return new TDerived;
return 0;
}
template<typename TBase, typename TDerived, typename TArg, typename... TArgs>
Base* get_classobject(const char* classname)
{
if(strcmp(classname,typeid(TDerived).name())==0)
return new TDerived;
return get_classobject<TBase,TArg,TArgs...>(classname);
}
EDIT :
, .
typeif(sometype).name() /.
static const char* name Derived, , (, , , factory)