Reputation: 229
I am trying to implement Template specialization. I delcared template and class:
template <class T>
class Person{
public:
Person(char one, T two){
this -> prv = one;
this -> druh = two;
}
void explain();
private:
char prv;
T druh;
};
and declared its getter
template <class T>
void Person<T>::explain(){
cout << "Druh isnt char" << endl;
}
Now if i create object with data type other than char , it will indeeed output the "Druh isnt char" e.g
Person <int> obj('a',5);
obj1.explain(); // "Druh isnt char"
I want to use specialization , so when the 2nd argument is char it will say "Druh is char"
I tried it using :
/********* Template specialization ***********/
template<>
class Person<char>{
public:
Person(char one, char two){
this-> prv = one;
this-> druh = two;
}
void explain();
};
and defined explain method again
void Person<char>::explain(){
cout << "Druh is a char " << endl;
}
But i am getting this error
'class Person' has no member named 'prv'|
Why is this happening? Should it take the private variables from first declaration of class Person? Doesnt templat<>
says to compiler that i am not creating another Object just using template specification?
Upvotes: 0
Views: 70
Reputation: 218323
You may specialize only the method:
template <>
void Person<char>::explain(){
cout << "Druh is char" << endl;
}
Upvotes: 1
Reputation: 1006
A simpler way of achieving what you want to do is this:
template <typename T>
class A {
public:
A() : c('z') {
}
void printChar() {
std::cout << "Not a char!" << std::endl;
}
private:
char c;
};
template <>
void A<char>::printChar() {
std::cout << c << std::endl;
}
Since what you want is to specialize the member function, and not the entire class.
Upvotes: 3