Defining a C ++ Template Specialization Method

The following code works fine, a simple template class with definition and usage

#include <string> #include <iostream> using namespace std; template<class T> class foo{ public: string what(); }; template<class T> string foo<T>::what(){ return "foo of type T"; } int main(){ foo<int> f; cout << f.what() << endl; } 

If I then add the following (above the main, but after declaring the template class foo;)

 template<> class foo<char>{ public: string what(); }; template<> string foo<char>::what(){ return "foo of type char"; } 

I get an error from g ++

Line 19: error: template-id 'what <>' for 'std :: string foo :: what ()' does not match any template

Here is the code that shows the error: http://codepad.org/4HVBn9oJ

What obvious mistake am I making? Or is this not possible with C ++ templates? Will all inline methods be defined (with template definition <> foo)?

Thanks again.

+4
source share
3 answers
 template<> class foo<char>{ public: string what(); }; /*template<>*/ string foo<char>::what(){ return "foo of type char"; } 

You do not need template<> . foo<char> already a full type after it specializes.

+8
source

Writing this as:

 #include <string> #include <iostream> using namespace std; template<class T> class foo{ public: string what(); }; template<class T> string foo<T>::what(){ return "foo of type T"; } template<> class foo<char>{ public: string what(); }; string foo<char>::what(){ return "foo of type char"; } int main(){ foo<char> f; cout << f.what() << endl; } 

works as expected.

+2
source

If I then add the following (above the main one, but before the declaration of the template class foo;)

Define specialization after specialization.

By the time the compiler sees a specialization, you first need to know the class template for which it is a specialization. Logically, the specialization should look after the generic class template.

0
source

All Articles