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?
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.
Method 2: C++14
In this case you need to remove the initializer
0from the in-class declaration of the static data member template.