[英]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.