Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template specialisation method definition

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

#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 main, but after the declaration of 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 declaration

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

What obvious misstake am I making? Or is this not possible with c++ templates? Will defining all the methods inline (with the defintion of template<> foo) work?

Thanks again all.

like image 843
cjh Avatar asked Dec 28 '22 22:12

cjh


1 Answers

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

You don't need that template<>. foo<char> is already a complete type after it's specialized.

like image 130
kennytm Avatar answered Dec 31 '22 09:12

kennytm