Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. The C++ Standard Library provides many useful functions within a framework of connected templates.
Major inspirations for C++ templates were the parameterized modules provided by CLU and the generics provided by Ada.
There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic.
A function template behaves like a function except that the template can have arguments of many different types (see example). In other words, a function template represents a family of functions. The format for declaring function templates with type parameters is:
Both expressions have the same meaning and behave in exactly the same way. The latter form was introduced to avoid confusion, since a type parameter need not be a class. (it can also be a basic type such as int
or double
.)
For example, the C++ Standard Library contains the function template max(x, y)
which returns the larger of x
and y
. That function template could be defined like this:
This single function definition works with many data types. Specifically, it works with all data types for which > (the greater-than operator) is defined. The usage of a function template saves space in the source code file in addition to limiting changes to one function description and making the code easier to read.
A template does not produce smaller object code, though, compared to writing separate functions for all the different data types used in a specific program. For example, if a program uses both an int
and a double
version of the max()
function template shown above, the compiler will create an object code version of max()
that operates on int
arguments and another object code version that operates on double
arguments. The compiler output will be identical to what would have been produced if the source code had contained two separate non-templated versions of max()
, one written to handle int
and one written to handle double
.