Template class type-specific functions
Asked Answered
O

2

6

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

public:
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{
 private:
  int x, y;
 public:
  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>

though

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?

Oarlock answered 21/11, 2016 at 14:3 Comment(1)
template<> void List<Point>::Print()Gerlachovka
W
9

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..
}
Watersick answered 21/11, 2016 at 14:14 Comment(6)
Does it goes in class body? Or outside of it?Oarlock
@YuryElburikh Outside of it.Watersick
now it tells me that "no member function "Print" is declared in List<int>"Oarlock
@YuryElburikh well an int is not a Point. You should still provide a fallback implementation for Print for the other cases.Watersick
And what if i only want Print for ints and Points? I did 'template<> void List<int>::Point();' 'template<> void List<Point>::Print();'Oarlock
@YuryElburikh You still need a fallback one that then does nothing.Watersick
W
1

However, as template can take classes as T, one can imagine, that i would need different implementations of Print() for that very cases

Not at all. You can have a single implementation of Print for every type of object - this is why templates are powerful.

One way to do what you want would be to define the stream operator << in Point, and have a generic Print() method in List. This makes Print available to more than just Point.

More generality ftw.

Wescott answered 21/11, 2016 at 14:57 Comment(1)
Hmm, this approach I like a whole lot more, however, for this project I have to use Point provided without any modifications to itOarlock

© 2022 - 2024 — McMap. All rights reserved.