I would like to be able to initialize a class from a string (I give "MyClass" and it would create an object MyClass).
I know it is not possible to do that so I created a class that has a map with a string as a key and a pointer to a function (that creates the object) as a value.
Creating dynamically the object is not a problem with this and my map.
template<typename T> JsonSerializable* createInstance() { return new T; }
My problem is that I want to add dynamically the classes to my map. Is that possible ? How can I do :
void MyFactory::addNewClass(std::string& name, class c)
{
map[name]=&createInstance<c>();
}
Can I pass a pointer or something to the class itself (not the object) ? And use that to create dynamically everything.
If it is not possible I will have to hardcode it.
Ok.. So if you're using C++11 then lambdas can be of some help in getting the generic behaviour you're looking for.
First of all, we need a SuperBase
from which all the classes shall be derived like this
class SuperBase {};
class A : public SuperBase {};
class B: public SuperBase {};
Then create a map which takes std::string
as key and std::function
as value.
map<string,std::function<SuperBase*()>> myMap;
The function return type is SuperBase
and the addNewClass
function can be defined as
template <typename type>
void addNewClass(std::string name) {
myMap[name] = []() { return new type();};
}
So from the main function you can call the function as
addNewClass<A>("A");
addNewClass<B>("B");
Then while iterating you can call the function to get you the desired pointer
for( auto mapPair : myMap) {
cout<<mapPair.first<<endl;
SuperBase * sBase = mapPair.second();
}
Remember, you need virtual
functions in SuperBase
to have polymorphic behaviour and then everything should work
Hope it helps