4

I am currently learning C++ in-depth, and I have come across something that has stumped for a couple hours now. Why is it when I make a template and then specialize it, that I can't call or define that function for the specialized version? The compiler complains, and I have scoured Google for a possible hint as to what I am doing wrong, but to no avail. I am very sure it is something very simple that I am overlooking:

template <typename T>
class C { };

//specialization to type char
template <>
class C <char> 
{
  public:
    void echo();
};

//compiler complains here
template <>
void C <char> :: echo() 
{
  cout << "HERE" << endl;
}

error: template-id ‘echo<>’ for ‘void C::echo()’ does not match any template declaration

Demo.

iammilind
  • 65,167
  • 30
  • 162
  • 315
jrd1
  • 9,642
  • 4
  • 31
  • 49
  • possible duplicate of [template-id does not match any template delcaration](http://stackoverflow.com/questions/4694181/template-id-does-not-match-any-template-delcaration) – GWW Oct 28 '11 at 04:49

1 Answers1

7
//specialization to type char
template <>
class C <char>
{
  public:
    void echo();
};

//template<>  <----- don't need to mention template<> here
void C <char> :: echo()
{
  cout << "HERE\n";
}

P.s. Never say endl when you mean '\n'. What is the C++ iostream endl fiasco?

Community
  • 1
  • 1
Robᵩ
  • 154,489
  • 17
  • 222
  • 296
  • 1
    Thanks @Rob! Last question, why does the function "echo()" not need a template specifier? – jrd1 Oct 28 '11 at 05:02
  • 2
    @jrd1, because `echo()` is not a `template` function by itself. It's a member method of a `template class`. – iammilind Oct 28 '11 at 05:08