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)

6
  • please add the error message. Commented Apr 10, 2017 at 14:35
  • 1
    Are you defining singletons anywhere? Commented Apr 10, 2017 at 14:35
  • yes it's in the private section of the class Commented Apr 10, 2017 at 14:39
  • 1
    Possible duplicate of Unresolved external symbol on static class members Commented Apr 10, 2017 at 14:42
  • 1
    btw a map of Singletons called singletons is kind of an oxymoron Commented Apr 10, 2017 at 14:51

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.