静态模板函数访问静态 class 成员
Static Template function access static class member
我在 class 中有一个静态模板函数,它需要访问同一个 class 中的静态地图,但在尝试访问地图时我一直收到未解决的外部错误。有什么想法吗?
代码如下:
class Singleton
{
private:
static std::map<size_t, Singleton*> singletons;
public:
template<typename T>
static T* Get()
{
size_t type = typeid(T).hash_code();
if (singletons[type] == nullptr)
singletons[type] = new T();
return (T*)singletons[type];
}
};
错误信息:
error LNK2001: unresolved external symbol "private: static class std::map,class std::allocator > > Singleton::singletons" (?singletons@Singleton@@0V?$map@IPAVSingleton@@U?$less@I@std@@V?$allocator@U?$pair@$$CBIPAVSingleton@@@std@@@3@@std@@A)
static class 成员需要在编译单元中定义和声明(在您的情况下 singletons
成员)
您需要在 .cpp
文件中添加此行:
std::map<size_t, Singleton*> Singleton::singletons;
我在 class 中有一个静态模板函数,它需要访问同一个 class 中的静态地图,但在尝试访问地图时我一直收到未解决的外部错误。有什么想法吗?
代码如下:
class Singleton
{
private:
static std::map<size_t, Singleton*> singletons;
public:
template<typename T>
static T* Get()
{
size_t type = typeid(T).hash_code();
if (singletons[type] == nullptr)
singletons[type] = new T();
return (T*)singletons[type];
}
};
错误信息:
error LNK2001: unresolved external symbol "private: static class std::map,class std::allocator > > Singleton::singletons" (?singletons@Singleton@@0V?$map@IPAVSingleton@@U?$less@I@std@@V?$allocator@U?$pair@$$CBIPAVSingleton@@@std@@@3@@std@@A)
static class 成员需要在编译单元中定义和声明(在您的情况下 singletons
成员)
您需要在 .cpp
文件中添加此行:
std::map<size_t, Singleton*> Singleton::singletons;