我正在尝试实现模板特化。我声明了模板和类:
template <class T>
class Person{
public:
Person(char one, T two){
this -> prv = one;
this -> druh = two;
}
void explain();
private:
char prv;
T druh;
};
并声明它的getter
template <class T>
void Person<T>::explain(){
cout << "Druh isnt char" << endl;
}
现在,如果我创建数据类型不是 char 的对象,它确实会输出“Druh isnt char”,例如
Person <int> obj('a',5);
obj1.explain(); // "Druh isnt char"
我想使用 specialization ,所以当第二个参数是 char 时,它会说 "Druh is char"
我试过使用:
/********* 模板特化 ***********/
template<>
class Person<char>{
public:
Person(char one, char two){
this-> prv = one;
this-> druh = two;
}
void explain();
};
再次定义explain方法
void Person<char>::explain(){
cout << "Druh is a char " << endl;
}
但是我收到了这个错误
'class Person' has no member named 'prv'|
为什么会这样?它应该从 Person 类的第一个声明中获取私有(private)变量吗?没有templat<>
对编译器说我不是仅使用模板规范创建另一个对象?
最佳答案
一个更简单的实现你想做的事情的方法是:
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;
}
因为你想要特化成员函数,而不是整个类。
关于c++ - 带有类的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35798084/