gpt4 book ai didi

c++ - 如何正确注册?

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:56 25 4
gpt4 key购买 nike

我有一个工厂类来注册一个类型

class Factory
{
public:
template<class T>
static void regist()
{
mMap[T::type()] = [](){return new T();};
}

static Base* create(string type)
{
... // use map to find the function to create a new object
}

private:
static map<string, function<Base* ()>> mMap;
};

map<string, function<Base* ()>> Factory::mMap;

和 Base 的具体类 T

class A : public Base
{
public:
static string type() { return "A"; }
static bool sRegist;
A() {}

};

bool A::sRegist = []() -> bool {
Factory::regist<A>();
return true;
}();

但是,代码在运行时崩溃了。我认为这是由于静态成员的不确定初始化顺序。如何让它发挥作用?谢谢。

最佳答案

mMap 放在静态函数中,如下所示:

class Factory
{
public:
template<class T>
static void regist()
{
getMap()[T::type()] = [](){return new T();};
}

// ...

private:
static map<string, function<Base* ()>>& getMap() {
static map<string, function<Base* ()>> mMap;
return mMap;
}
};

在这种情况下,mMap 将在函数被调用时立即初始化。

关于c++ - 如何正确注册?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com