Understanding templates
Templates are useful in the sense that they allow multiple types to be used instead of set types.
In other words, a simple function could be written as follows:
The above function will return the max of two double precision numbers.
But say you didn't want to only find the max of two double precision numbers. Say you wanted to
be able to find the max of any number (long, float etc...). Without the use of a template, you
could not do this. Here is what the new max function would look like:
The template is defined above where class can be any type either pre defined or user defined. These
include int, float, short, long, etc... The letter or name following the keyword class does not always
have to be a capital T but it should be a useful name or letter.
The above functions allows us to find the max of anything. The T is the new data type. If we did not do this,
we would have to rewrite the max function for every conceivable type in C++ (thankfully there is
the template).
A template works for a class as well. In a similar fashion:
Now this class could be used with any type. Here is a short program demonstrating the template
of the max function above:
Just note that you cannot template the main function! Do not try it as it will confuse the
execution of the program.
Here is an exmaple using a template class called Point: