5

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
  • 68,093
  • 33
  • 169
  • 336
jrd1
  • 10,358
  • 4
  • 34
  • 51
  • 1
    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

2 Answers2

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

//template<>  <----- don't 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?

Hari
  • 1,561
  • 4
  • 17
  • 26
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 2
    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
0

Robᵩ's answer fixes the issue. It will be good to know more about the reason.

From Explicit (full) template specialization:

Members of specializations

When defining a member of an explicitly specialized class template outside the body of the class, the syntax template<> is not used, except if it's a member of an explicitly specialized member class template, which is specialized as a class template, because otherwise, the syntax would require such definition to begin with template required by the nested template.

Hari
  • 1,561
  • 4
  • 17
  • 26