[英]Static Template function access static class member
我在一个类中有一个静态模板函数,该类需要访问同一类中的静态映射,但是在尝试访问该映射时,我始终收到未解决的外部错误。 有任何想法吗?
这是代码:
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];
}
};
错误信息:
错误LNK2001:无法解析的外部符号“私有:静态类std :: map,类std :: allocator>> Singleton :: singletons”(?singletons @ Singleton @@ 0V?$ map @ IPAVSingleton @@ U?$ less @ I @ STD @@ V'$分配器@ U&$对@ $$ CBIPAVSingleton @@@ STD @@@ 3 @@ STD @@ A)
静态类成员需要在编译单元中定义和声明(在您的情况下为singletons
成员)
您需要在.cpp
文件中添加以下行:
std::map<size_t, Singleton*> Singleton::singletons;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.