Search code examples
c++templatescompiler-errorstemplate-specialization

Defining and calling a C++ function of a specialized template


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.


Solution

  • //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?