【问题标题】:Static Template function access static class member静态模板函数访问静态类成员
【发布时间】:2017-04-10 14:33:47
【问题描述】:

我在一个类中有一个静态模板函数,该函数需要访问同一个类中的静态映射,但在尝试访问映射时不断收到未解决的外部错误。有什么想法吗?

代码如下:

 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,class std::allocator > > Singleton::singletons”(?singletons@Singleton@@0V?$map@IPAVSingleton@@U?$less @I@std@@V?$allocator@U?$pair@$$CBIPAVSingleton@@@std@@@3@@std@@A)

【问题讨论】:

标签: c++ templates static linker-errors


【解决方案1】:

需要在编译单元中定义和声明静态类成员(在您的情况下为 singletons 成员)

您需要将此行添加到.cpp 文件中:

std::map<size_t, Singleton*> Singleton::singletons;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多