Template specialization: does not match template declaration

When I study template specialization, I use a very simple example, but I still have an 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; } 

Error:

 line 20: error: template-id 'chgchr<>' for 'char chrrr<char>::chgchr(char)' does not match any template declaration 

I wonder why the dose does not match? And if I define chgchr in the body definition class, and not outside of it, it works very well.

+4
source share
2 answers

You explicitly specialized the class, as a result of which an instance of type chrrr<char> was completely created. When defining a member function, you do not need to specify template arguments. Just:

 char chrrr<char>::chgchr(char c){ return c+2; } 

However, it looks like you specialize in the whole class to specialize in one function. You can do it 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; } 
+13
source

Specialized class templates result in a normal class with a funny name, not a template. When you specialize in chrrr<char> , it is no longer a template, and the implementation of its class members is not a specialization template. Therefore, you should simply write:

 char chrrr<char>::chgchr( char c ) ... 

template<> you set yourself that still another template must be specialized, which is not so.

+3
source

All Articles