Writing your first templates
It is now time to see how templates are written in the C++ language. In this section, we will start with three simple examples, one for each of the snippets presented earlier.
A template version of the max
function discussed previously would look as follows:
template <typename T> T max(T const a, T const b) { return a > b ? a : b; }
You will notice here that the type name (such as int
or double
) has been replaced with T
(which stands for type). T
is called a type template parameter and is introduced with the syntax template<typename T> or typename<class T>
. Keep in mind that T
is a parameter, therefore it can have any name. We will learn more about template parameters in the next chapter.
At this point, this template that you put in the source code is only a blueprint. The compiler will generate code from it based on its use. More precisely, it will instantiate a function overload for each type...