c++ - 在编译时生成某种子类/类型注册表?

标签 c++

我正在编写一个应用程序(一个游戏),它有一个父类的多个子类,它们都需要在 map 中注册,以便在运行时读取的文件中引用它们。

例如,如果我有一个 Subclass 类,并且我的文件指定它需要一个 "Subclass" 的实例,我的文件解析器将查找该值在此映射中,它是一个 std::function,它初始化子类的实例并将其作为父类指针返回。

我目前通过 registry.cpp 文件完成此操作,我必须在其中手动输入每个新类,如下所示:

void register_all ()
{
    registry["Subclass1"] = [] () { return new Subclass1 (); };
    registry["Subclass2"] = [] () { return new Subclass2 (); };
    // ... etc
}

我注意到其他具有类似设置的应用程序似乎能够使用宏自动注册这些子类(例如 Valve Software's Source Engine, which uses a DECLARE_CLASS macro in the class's cpp file, with no need for a header file or any other configuration whatsoever。)

如何在我自己的应用程序中实现这种零配置“子类注册”?

最佳答案

这些宏基本上声明了一个文件范围变量(在标识符中包含类名以使其唯一)。该变量的构造函数调用一个函数来注册 lambda。

例如。像这样:

std::map<std::string, std::function<Parent*()>>  actions;
class RegisterClass
{
    public:
        RegisterClass(std::string const& className, std::function<Parent*()>&& action)
        {
            actions.insert(std::make_pair(className, std::move(action)));
        }
};
#define REGISTERCLASS(Class)              \
    static RegisterClass   tmpMyUniqueName ## Class( # Class,  [](){return new Class;})

                                    //               ^ Single # quotes the identifier
                                    //     ^^ Double ## combines the pre and post identifiers.

如果您将以上内容用于:

class X: public Parent {};
class Y: public Parent {};
REGISTERCLASS(X);
REGISTERCLASS(Y);

您将获得:

class X: public Parent {};
class Y: public Parent {};
static RegisterClass tmpMyUniqueNameX( "X", [](){return new X;});
static RegisterClass tmpMyUniqueNameY( "Y", [](){return new Y;});

关于c++ - 在编译时生成某种子类/类型注册表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51849030/

相关文章:

c++ - C++ 中的文件 channel

c++ - libcurl 内置压缩支持与否

c++ - 如何从另一个源文件调用 main.cpp 中的静态函数?

c++ - 如何判断 C++ 生成了什么模板

c++ - 'PyCObject_Import ("cairo", "CAPI")' C++ call yields segfault, ' import cairo' 在 python 上有效

c++ - 如何在C++模板元编程中返回不止一种类型?

c++ - 数组溢出 C++(在 arr[0])?

c++ - 如何返回 constexpr 的元组

c++ - 动态分配数组的矩阵乘法;结果不正确

c++ - 如何处理模板化代码中的变量const?