Defining function templates
Function templates are defined in a similar way to regular functions, except that the function declaration is preceded by the keyword template
followed by a list of template parameters between angle brackets. The following is a simple example of a function template:
template <typename T> T add(T const a, T const b) { return a + b; }
This function has two parameters, called a
and b
, both of the same T
type. This type is listed in the template parameters list, introduced with the keyword typename
or class
(the former is used in this example and throughout the book). This function does nothing more than add the two arguments and returns the result of this operation, which should have the same T
type.
Function templates are only blueprints for creating actual functions and only exist in source code. Unless explicitly called in your source code, the function templates will not be present in the compiled executable. However, when...