When I study the template specialization, I use a very simple example, but I still got error.
#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;
}
The error said:
line 20: error: template-id ‘chgchr<>’ for ‘char chrrr<char>::chgchr(char)’ does not match any template declaration
I wonder why it dose not match? And if I define chgchr in class definition body rather than out side, it works very well.
You have explicitly specialized the class, resulting in a fully instantiated type called chrrr<char>
. You don't need to give the template arguments when defining the member function. Simply:
char chrrr<char>::chgchr(char c){
return c+2;
}
However, it seems you are specializing the whole class just to specialize a single function. You can do that with:
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;
}
Specialized class templates result in a normal class with a funny name, and not a template. When you specialize chrrr<char>
, it is no longer a template, and the implementation of its class members are not template specializations. So you should simply write:
char
chrrr<char>::chgchr( char c ) ...
The template<>
you put in front says that there is still another template to be specialized, which is not the case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.