4

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.

cjh
  • 1,113
  • 1
  • 9
  • 21

3 Answers3

8
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.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
2

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.

hkaiser
  • 11,403
  • 1
  • 30
  • 35
0

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

Define the specialization after the generic class template.

By the time the compiler sees the specialization, it first needs to know the class template of which this is a specialization. So logically, the specialization should appear after the generic class template.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Sorry it should have said AFTER not before, if you had looked at the codepad this would have been clear. Thank you for your time anyway. – cjh Apr 18 '11 at 23:06