0

I have a static template function inside a class that needs to access a static map inside the same class but I keep getting a unresolved external error when trying to access the map. Any Ideas?

Here's the code:

 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 Message:

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)

eriksimon
  • 25
  • 7

1 Answers1

1

static class members need to be defined and declared in a compilation unit (in your case singletons member)

You need to add this line in a .cpp file:

std::map<size_t, Singleton*> Singleton::singletons;
Raxvan
  • 6,257
  • 2
  • 25
  • 46