Reputation: 10716
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.
Upvotes: 5
Views: 1317
Reputation: 168626
//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?
Upvotes: 8
Reputation: 1803
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.
Upvotes: 0