如何使用cpp中的作用域解析运算符创建专门化模板


template<class t> class Temp{
static t x;
public:
Temp(){};
t increment();
~Temp(){/*body of destructor is important.*/};
};
template<class t>t Temp<t>::x;
template<class t> t Temp<t>::increment(){
return ++x;
}
/*Template specialization starts.*/
template<>class Temp<int>{
int x;
public:
Temp():x(0){};
int increment();
~Temp(){};
};
/*Below is the error part.*/
template<>int Temp<int>::increment(){
return 0;
}

问题出在最后一块代码上。编译错误->错误:模板id"increment<>'"int Temp::increment(("与任何模板声明都不匹配

您不必使用模板<>使用专门的成员函数,因为编译器知道您正在专门化Temp for int类型。因此,空模板<>给出错误。

int Temp<int>::increment() {
return ++x;
}

template用于告诉编译器T是template-param,仅此而已。但在您的情况下,您专门针对int类型,因此不必指定template<>。模板<>仅适用于类,而不适用于在类外定义的成员函数。

最新更新