I need to port the following Java concept into C++ :
Hash map holding object id key and class type value:
Map<String, Class> _objectsBank = new HashMap<>();
Somewhere in the init method I fill the bank like this:
_objectsBank .put("CLASS_ID_1", MyClass1.class);
_objectsBank .put("CLASS_ID_2", MyClass2.class);
....
Then , later ,I construct an instance of one of the classes saved in that bank by demand.
Kind of “lazy” init :
private MyClass initNewProg(String name) {
MyClass instance;
try {
Class cl = _objectsBank.get(name);
java.lang.reflect.Constructor co = cl.getConstructor(String.class);
instance= (MyClass) co.newInstance(name);
return instance;
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
e.printStackTrace();
return null;
}
}
How would I do it in C++ ? How can I set a class type as std::map value so that I can query it later to construct an appropriate instance from it?
Is there something like this in Boost libraries?
Take a look at Is there a way to instantiate objects from a string holding their class name? and Instantiating classes by name with factory pattern, which describe the problem and multiple approaches with pros & cons of each ones. The examples cover registration of contructors for classes, which solves the issue with multiple if-statements you mentioned in @Karthik T’s solution.