I have a long list of classes and I want to instantiate one according to a string.
I currently have code (that works) like the following:
BaseClass* InstantiateClass(const string& key){
if(key == "SpecificClass1"){
SpecificClass1* p = new SpecificClass1();
return p;
}
else if(key == "SpecificClass2"){
SpecificClass2* p = new SpecificClass2();
return p;
}
...
else if(key == "SpecificClass999"){
SpecificClass999* p = new SpecificClass999();
return p;
}
else{
throw("Unknown class");
}
}
I would like to replace that using a map. Something like the following code (which doesn't work):
BaseClass* InstantiateClass(const string& key){
map<string, BaseClass*> MapOfClasses;
MapOfClasses["SpecificClass1"] = SpecificClass1; // Compile error
MapOfClasses["SpecificClass2"] = SpecificClass2;
...
MapOfClasses["SpecificClass999"] = SpecificClass999;
(MapOfClasses[key])* p = new MapOfClasses[key]();// Most likely wrong
return p;
}
> I have a long list of classes and I want to instantiate one according to a string
> I currently have code (that works) like the following:
> I would like to replace that using a map.
That is to say, ideally:
a. Adding a new derived class should require nothing more than adding the code for that class
(should not require breaking any code elsewhere in the program).
b. The determination of whether a string is the right string to instantiate an object should be localised to the appropriate derived class implementation (and the logic for this could be more involved than just looking up a string in a map: for instance, instantiate the object if the string matches a regular expression.)