2

I want to assign two different values to A<int> and A<char>,then each kind of instantialized classes have their own static member 'a',but the program compile failed.

Here's the code.

#include <iostream>
using namespace std;
template<class T>
class A {
private:
    static int a;
public:
    friend ostream& operator<<<T>(ostream& os, A<T>& p); 
};
template<class T>
ostream& operator<<(ostream& os, A<T>& p){
    cout << p.a;
    return os;
}
template<class T>int A<T>::a = 5;
template<class T>char A<T>::a = 50;//error:the declaration is not compatible with the previous "int A<T>::A"declaration
int main()
{
    A<int> v1, v2, v3;
    A<char>v11, v22, v33;
    cout << v1<<" "<<v2<<" "<<v3<<endl;

}

So what should I do?

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
Victor Hut
  • 35
  • 5
  • You mean template specialization like this: https://stackoverflow.com/questions/13404695/c-how-to-initialize-static-variables-of-a-partial-template-specialization ? – pptaszni Jun 22 '22 at 16:48
  • 3
    If you only want to specify values for `A` and `A`, why are you doing `templateint A::a = 5;`? Since `A::a` is still supposed to be an `int`, not a `char`, what is the entire second line supposed to mean at all? Is [this](https://godbolt.org/z/qGKe6GMPa) what you're looking for? – Nathan Pierson Jun 22 '22 at 16:55

1 Answers1

2

You need to do an explicit specialization which you do by writing an empty template declaration and replacing T in A<T> with the type you want.

template<> int A<int>::a = 5;
template<> int A<char>::a = 50;
David G
  • 94,763
  • 41
  • 167
  • 253