C++ Templates

Most of the information is taken from C++ Templates: The Complete Guide, by David Vandervoorde and Nicolai M. Josuttis.

C++ templates allow you to write functions or classes that prescribe behavior for an arbitrary data type. Instead of duplicating code for each type that it should handle, you write the logic once and indicate that the underlying data is arbitrary.

Two-Phase Lookup

Templates are compiled twice (at least): during definition time, the code is checked while ignoring the template parameters. Syntax errors can be revealed at this stage and normal errors for code that isn’t inherently tied to the template parameters. During instantiation time, the code is checked again, but this time it includes all code, even that code that is tied to the template parameters.

This leads to

Function Templates

template<typename T>
T& max(T& left, T&right)
{
    return left < right ? left : right;
}

When compiled, entities are generated for each type the function is used for. This process is called instantiation. If the above function was only ever called with int values, an int instance will be generated with concrete int type, e.g.

max(1,2);

Here, the type is automatically deduced to be int. No automatic conversion is allowed here, the types must be the same and support all of the operations performed in the body of the function. You can alternatively specify or qualify exactly the type of T:

max<double>(4, 4.2);

C++ Templates

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top