“undefined reference” to static member of template class accessed from static method

前端 未结 3 1432
自闭症患者
自闭症患者 2020-12-11 02:39

I have a static class method that needs access to a pointer MyTypePointer that therefore has to be declared static. Since it is a template class I have to put the methods in

相关标签:
3条回答
  • 2020-12-11 03:06

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

    template <class A, class B>
    typename PathfindingClass<A, B>::MyType*
    PathfindingClass<A, B>::MyTypePointer;
    
    0 讨论(0)
  • 2020-12-11 03:13

    You can still define the template member and explicitly instantiate it for all needed specializations. If you insist in having a state data member of a class template that's roughly what's needed.

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

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

    The local variable is initialized the first time the function is called and a reference to it can safely be used. This approach also works for templates.

    Note that I still recommend to avoid global variables! They cause many problems in the long-term and short-term benefit of using them is a huge debt which normally doesn't pay off.

    0 讨论(0)
  • 2020-12-11 03:25

    It is a late answer for full reference, as this question is linked as a reference 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 just to define the static field after the 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;
    }
    
    0 讨论(0)
提交回复
热议问题