Issue
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?
Solution
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;
Answered By - David G Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.