Yury  Elburikh Yury Elburikh - 1 year ago 96
C++ Question

Template class type-specific functions

Ok, so i have this template class, which is kinda like one-way list.

template <typename T> List

and it have this inside function print

void Print();

which, as you can guess, prints the list contents from begining to end;
However, as template can take classes as T, one can imagine, that i would need different implementations of Print() for that very cases. For example, I have another class Point

class Point{
int x, y;
int getX();
int getY();

so i want Print specifically designed for Points. I tried this:

void List<Point>::Print();

but compiler tells me

prototype for void List<Point> Print() doesn match any in class List<Point>


candidates are: from List<T> [with T = Point] void List<Point>::Print()

For me it seems like the same fucntion. What's wrong? And how do I write T-specific template class functions?

Answer Source

You use explicit template specialization to specialize behaviour of Print for specific types.

For example, for Point:

template <> // No template arguments here !
void List<Point>::Print() // explicitly name what type to specialize
  //code for specific Point Print behaviour..
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download