静态模板函数访问静态类成员

时间:2017-04-10 14:33:47

标签: c++ templates static linker-errors

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

以下是代码:

 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:未解析的外部符号&#34; private:static class std :: map,class std :: allocator&gt; &GT;单::单身&#34; (?单身@ @@辛格尔顿0V?$地图@ @@ IPAVSingleton U&$ @少I @ @@性病V'$分配器@ U&$对@ $$ CBIPAVSingleton @@@ STD @@@ 3 @@ @性病@A)

1 个答案:

答案 0 :(得分:0)

需要在编译单元中定义和声明静态类成员(在您的情况下为function get_confirmation_email(cart, delivery_date, render_confirmation_email,done_callback) { $.ajax({ type: "GET", url:"/confirmation_email", async: false, success:function(data) { console.log("success"); // render_confirmation_email called when data is ready var d = (render_confirmation_email(data, cart, delivery_date)); console.log("Rendering done") console.log(d) return d }, complete : function(){ if(typeof done_callback === "function") done_callback(); } }) } 成员)

您需要在singletons文件中添加此行:

.cpp