...

/

Writing Our First Templates

Writing Our First Templates

Learn and practice template syntax in C++ through hands-on template creation.

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;
}
The template version of the max function

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 ...