Let’s try something a little bit more complicated.
Consider the template class LinkedList:
We defined linked lists of different types as follows:
We can also use a class type to define a linked list of more complex structures.
For instance, a point is defined by its x and y coordinates.
We can create a linked list of points as follows:
Note that the member functions receive and return variables
of type Point:
We have defined Point with coordinates of type double,
but maybe we also want points with coordinates of type int or float.
Define Point as a template to give this flexibility:
We can use the template class Point to define different types
of linked lists of points:
Note that there MUST be a space between ‘>’ and ‘>’.
A common error is to forget this space.
Unfortunately, the symbol ‘»’ has a separate meaning in C++.
If you forget the space, the compiler will interpret ‘»’
as the right shift operator
and generate a whole bunch of (unintelligible) error messages.
Two or more template parameters
A template can have two or more type parameters.
For instance, a circle is defined by the x and y coordinates
of its center and its radius:
We may also want a circle whose x and y coordinates are integers
and its radius is type double.
Or perhaps we also want the x and y coordinates to have type double
and the radius to be an integer.
We can define a template class with separate types
for the coordinates and the radius.
When we create the circle, the k’th type in the template parameter list
is set to be the k’th type in the template argument list.
We can create a linked list of circles as follows:
We can also use the Point class in defining the coordinates
of the center of the circle:
A different way to use the class Point is as follows:
Template class CircleB gives more flexibility than template class CircleA.
For instance, CircleB could have different types for coordinates x and y
or could have other data stored with the point.
On the other hand, anyone writing a new class to be used as a POINT_TYPE
must remember to have x and y fields in the class.
The flexibility of CircleB also creates the potential for more
things to go wrong.
Template classes can have more than two parameters.
For instance, in computer graphics the representation
of a circle may include an r,g,b color and an opacity.
Templates and compiler errors
With all but the simplest templates, compiler errors can be extremely confusing.
Unless you are extremely good at template programming,
it is often better to first code a class without using templates
and then convert to a template class.
The following code generates a fairly simple compiler error:
Can you spot the error?
Compiling the function gives the following error message:
Can you determine the error after reading the error message?