MoustacheSpy
MoustacheSpy

Reputation: 763

c++ cant define a reference to static template member with the parent class pointer as a type

What I am trying to do:

Make some sort of "Registry" for my class so that every instance can be looked up using a unique string (i am checking if its unique or not but its omitted in the examples below).

My Problem:

I cant declare a reference to my static member. I dont know why.

Code (with parts omitted)

//component.h
template <class t>
class ComponentTable : InstanceCounted<ComponentTable<t>> //Instance Counted is a template that automatically counts the instances
{
private:
    //Omitted
    static std::unordered_map<std::string, ComponentTable*> componentRegistry;
public:
    //Omitted, the insert happens in the constructor and it gets removed in the destructor
}
//component.cpp
template<class t>
std::unordered_map<std::string, ComponentTable<t>*> ComponentTable<t>::componentRegistry;
//---

What I have already tried

I really got no lead on this one so I kinda couldnt try much :(

The Error:

undefined reference to `ComponentTable<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::componentRegistry'|

This appears where I am trying to first use the member, which is in the constructor. I am doing the insert using the insert function with a simple std::pair of a correct type.

Other Data:

I hope this info is enough to help me out here ;)

Upvotes: 1

Views: 128

Answers (1)

YSC
YSC

Reputation: 40070

Since you're dealing with templates, you should define the static member in the header itself:

//component.h
template <class t>
class ComponentTable : InstanceCounted<ComponentTable<t>>
{
    static std::unordered_map<std::string, ComponentTable*> componentRegistry;
};

template<class t>
std::unordered_map<std::string, ComponentTable<t>*> ComponentTable<t>::componentRegistry;

This is the simplest way to ensure a componentRegistry is instanciated for each ComponentTable<t>.

Upvotes: 1

Related Questions