Question:
Clear sky!
I'm reading a C++ tutorial. There's an example of class template refinement:
template<typename T> class MyCout
{
private:
T data;
public:
MyCout(T a): data(a) {};
void display() {cout << data << endl;};
};
template<> class MyCout<string>
{
private:
string data;
public:
MyCout(string a): data(a){};
void display() {cout << data.c_str() << endl;};
};
I decided to experiment and shorten the code a little, making the template not of the whole class, but only of the function:
class NewCout
{
public:
NewCout(){};
template<typename T> void display(T a){cout << a << endl;};
template<> void display<string>(string a){cout << a.c_str() << endl;};
};
But the compiler throws an error on line #6: invalid explicit specialization before '>' token .
What am I doing wrong?
And one more question in pursuit: how is it customary to design templates?
Answer:
C++ forbids partial specialization of methods, only class templates can be specialized. See the standard , paragraph 14.5.6. Why this was done is discussed here (warning: English langwidge inside!).
Apparently, the author of the book is wrong.
You can, however, override the template method (which is not the same).
Oh, shame on me. Here it works:
class C
{
public:
template<typename T>
void f(T t);
};
template<typename T>
void C::f(T t)
{
cout << t << endl;
}
template<>
void C::f<int>(int t)
{
cout << "(int specialization) " << t << endl;
}
Understood. In the example above the line, not partial , but full specialization. Partial specialization is still prohibited, as the spec says. Example :
class C
{
public:
template<typename T>
void f(T t);
};
template<typename T>
void C::f(T t)
{
cout << t << endl;
}
template<typename T> // ошибка: function template partial
void C::f<T*>(T* pt) // specialization ‘f<T*>’ is not allowed
{
cout << "(pointer specialization) " << *pt << endl;
}