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?
Templates are powerful features of C++ which allows us to write generic programs. We can create a single function to work with different data types by using a template.
There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
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..
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With