将 C++ 中的类从类类型实例化为 std::map 值

Mic*_* IV 0 c++ java reflection stl

我需要将以下 Java 概念移植到 C++ 中:

持有对象 id 键和类类型值的哈希映射:

 Map<String, Class> _objectsBank = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

在 init 方法的某个地方,我像这样填充银行:

    _objectsBank .put("CLASS_ID_1", MyClass1.class);
    _objectsBank .put("CLASS_ID_2", MyClass2.class);
    ....
Run Code Online (Sandbox Code Playgroud)

然后,稍后,我根据需要构造了保存在该银行中的类之一的实例。一种“懒惰”的初始化:

 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;
    }
 }
Run Code Online (Sandbox Code Playgroud)

我将如何在 C++ 中做到这一点?如何将类类型设置为 std::map 值,以便稍后查询以从中构造适当的实例?Boost 库中有这样的东西吗?

Nob*_*ody 5

您可以使用函数指针。由于您不能将函数指针指向构造函数,因此您必须使用工厂函数:

template <class Derived>
Base* create()
{
        return new Derived;
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将函数指针保存到映射中工厂函数的模板实例以构造您的派生类:

int main()
{
        std::map<std::string, Base*(*)()> classMap;
        classMap["Derived1"] = &create<Derived1>;
        classMap["Derived2"] = &create<Derived2>;

        delete classMap["Derived1"]();
        delete classMap["Derived2"]();   
}
Run Code Online (Sandbox Code Playgroud)

在Ideone上查看