c++templatesstaticvariable-templates

Error while using a static data member template


I am trying understand the concept of static data member templates. And i came across the following example in a book:

class Collection {
    public: 
    
    template<typename T>
    static T zero = 0;
}; 

When i try to execute the program it gives the error that:

undefined reference to `Collection::zero<int>'

To solve the above error i tried added the following code in the above program but it still gives error:

template<typename T> T Collection::zero = 0; //even after adding this it still gives error

Error now says:

duplicate initialization of 'Collection::zero'

My question is that is this a mistake(typo) in this example of the book. If yes, then what is the problem and how can i solve it?


Solution

  • Yes this is a typo in the book. The problem is that you've specified an initializer for the static data member template even though it is not inline.

    Solution

    There are 2 ways to solve this problem both of which are given below.

    Method 1: C++17

    In C++17, you can make use of the keyword inline.

    class Collection {
        public:
        
        
        template<typename T>
        inline static T zero = 0; //note the keyword inline here
    }; 
    //no need for out of class definition of static data member template
    int main(){
        int x =Collection::zero<int>;
    }
    

    Method 2: C++14

    In this case you need to remove the initializer 0 from the in-class declaration of the static data member template.

    class Collection {
        public:
        
        template<typename T>
        static T zero ; //note initializer 0 removed from here since this is a declaration
    }; 
    
    template<typename T> T Collection::zero = 0;
    int main(){
        int x =Collection::zero<int>;
    }