syko
syko

Reputation: 3627

How can I Declare/define/initialize a static member variable of template classes as static member variables of a class?

I have the following code:

template <typename T>
class A {
    public:
        static int a;
};

class B {
    public:
        static A<int> a1;
        static A<double> a2;
};

int B::a1::a = 0; --> It gives an error "a1 is not a class, namespace, enumeration"

(I am using llvm compiler in XCode. I can reproduce the problem with gcc as well.)

How can I Declare/define/initialize a static member variable of template classes as static member variables of a class?

Upvotes: 2

Views: 368

Answers (1)

songyuanyao
songyuanyao

Reputation: 172864

Static members are defined base on their class. a is static member of A, a1 and a2 are static members of B, you can't mix up their definition.

Define them seprately:

template <typename T>
int A<T>::a = 0;

A<int> B::a1;
A<double> B::a2;

If you want template specialization for definition of A<T>::a, it will look like:

template <typename T>
int A<T>::a = 0;
template <typename T>
int A<int>::a = 1;
template <typename T>
int A<double>::a = 2;

Then for A<int>::a the initial value will be 1, for A<double>::a will be 2, for other types like A<char>::a it will be 0. Note the definitions is still independent of the definitions of class B.

If you want to access a from B::a1, you could write B::a1.a; since a1 is a A<int>, the result is same as A<int>::a.

Upvotes: 4

Related Questions