使用类的模板专业化

时间:2016-03-04 14:06:34

标签: c++ templates c++11

我正在尝试实现模板专业化。我开始模板和课程:

?

并宣布其吸气剂

template <class T>
class Person{

public:

        Person(char one, T two){

            this -> prv  = one;
            this -> druh = two;

        }
        void explain();

private:

    char prv;
    T druh;

};

现在,如果我使用除char之外的数据类型创建对象,它将默认输出“Druh isnt char”,例如

template <class T>

void Person<T>::explain(){

    cout << "Druh isnt char" << endl;

}

我想使用特化,所以当第二个参数是char时,它会说 Person <int> obj('a',5); obj1.explain(); // "Druh isnt char"

我尝试使用:

/ *********模板专业化*********** /

"Druh is char"

再次定义解释方法

template<>

class Person<char>{

public:
        Person(char one, char two){

           this-> prv = one;
           this-> druh = two;

        }
        void explain();

};

但是我收到了这个错误

  

'class Person'没有名为'prv'|

的成员

为什么会这样?是否应该从类Person的第一次声明中获取私有变量?没有void Person<char>::explain(){ cout << "Druh is a char " << endl; } 对编译器说我不是只使用模板规范创建另一个对象吗?

2 个答案:

答案 0 :(得分:3)

实现您想要做的事情的一种更简单的方法是:

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;
}

因为你想要的是专门化成员函数,而不是整个类。

答案 1 :(得分:1)

您可能只专注于以下方法:

template <>
void Person<char>::explain(){
    cout << "Druh is char" << endl;
}