当我研究模板专业化时,我使用一个非常简单的例子,但我仍然有错误.
#include <iostream>
template <class T>
class chrrr{
public:
T chgchr(T c);
};
template < class T>
T chrrr<T>::chgchr(T c){
return c+1;
}
template <>
class chrrr<char>{
public:
char chgchr(char c);
};
template <>
char chrrr<char>::chgchr(char c){
return c+2;
}
using namespace std;
int main(){
char a='a';
int i=1;
chrrr<int> it;
chrrr<char> ch;
cout<<ch.chgchr(a)<<endl;
cout<<it.chgchr(i)<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误说:
line 20: error: template-id ‘chgchr<>’ for ‘char chrrr<char>::chgchr(char)’ does not match any template declaration
Run Code Online (Sandbox Code Playgroud)
我想知道为什么它不匹配?如果我在类定义体中而不是在外侧定义chgchr,它的效果非常好.
Jos*_*eld 13
您已明确专门化该类,从而导致调用完全实例化的类型chrrr<char>.定义成员函数时,不需要提供模板参数.只是:
char chrrr<char>::chgchr(char c){
return c+2;
}
Run Code Online (Sandbox Code Playgroud)
但是,似乎你专门研究整个班级只专注于一个单一的功能.你可以这样做:
template <class T>
class chrrr {
public:
T chgchr(T c);
};
template <class T>
T chrrr<T>::chgchr(T c){
return c+1;
}
// Explicitly specialize for the member function
template <>
char chrrr<char>::chgchr(char c){
return c+2;
}
Run Code Online (Sandbox Code Playgroud)
专门的类模板会产生一个具有有趣名称的普通类,而不是模板。当您特化时
chrrr<char>,它不再是模板,并且其类成员的实现也不是模板特化。所以你应该简单地写:
char
chrrr<char>::chgchr( char c ) ...
Run Code Online (Sandbox Code Playgroud)
你template<>前面说的还有另一个模板需要专门化,但事实并非如此。
| 归档时间: |
|
| 查看次数: |
10181 次 |
| 最近记录: |