"undefined reference" to the static member of the template class accessed from the static method

I have a static class method that needs access to the MyTypePointer pointer, so it must be declared static. Since this is a template class, I have to put the methods inside the header file, but I cannot define MyTypePointer in the header.

So, I get the "undefined Link" because MyTypePointer is not declared. How can I make this work / declare MyTypePointer.

myclass.h template <typename A, typename B> class PathfindingClass { typedef std::vector<GenericEdgeClass<A, B>*> MyType; static MyType *MyTypePointer; }; template <typename A, B> void MyClass<A, B>::MyMethod(int x, int y) { //do something with MyTypePointer } 

Thank you very much.

+6
source share
3 answers

In the template definition, static MyType *MyTypePointer; declares an object. You still need to determine outside the template class definition:

 template <class A, class B> typename PathfindingClass<A, B>::MyType* PathfindingClass<A, B>::MyTypePointer; 
+6
source

This is a late answer for complete reference, as this question is linked as a link to another question.

A minimal broken example of a static field declared, but not defined, could be:

 template<typename T> class A { public: static T val; static void init() { val=0; } }; int main() { // A::init(); A<double>::init(); return 0; } 

The fix is ​​to define a static field after class definition:

 template<typename T> class A { public: static T val; static void init() { val=0; } }; template<typename T> T A<T>::val; // only change here int main() { // A::init(); A<double>::init(); return 0; } 
+5
source

You can still define a member of the template and explicitly create it for all the required specializations. If you insist on having a state data element of a class template that roughly matches.

Given that global variables share all kinds of problems, including dependency problems during initialization, you are much better off wrapping your data member with a static member function:

 template <typenane T> class foo { // ... static X*& member() { static X* rc = ...; return rc; } }; 

A local variable is initialized the first time the function is called, and it can be safely used. This approach also works for templates.

Please note that I still recommend avoiding global variables! They cause many problems in the long-term and short-term benefits of their use - this is a huge debt that usually does not pay off.

+3
source

All Articles