Writing Our First Templates
Explore how to write your first C++ templates for functions, classes, and variables. Learn to use type template parameters, understand compiler instantiation, and see practical examples including max, quicksort, and vector templates.
We'll cover the following...
It’s now time to see how templates are written in the C++ language. In this lesson, we’ll start with three simple examples, one for each of the snippets presented earlier.
The max function
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;}
We’ll 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, so it can have any name. We’ll learn more about template parameters in the next section.
At ...