Function Templates
A function template defines a pattern for any number of functions whose definitions depend on the template parameters. You can overload a function template with a non-template function or with other function templates. You can even have a function template and a non-template function with the same name and parameters.
Function templates are used throughout the standard library. The
best-known function templates are the standard algorithms (such as
copy
, sort
, and for_each
).
Declare a function template using a template declaration header
followed by a function declaration or definition. Default template
arguments are not allowed in a function template declaration or
definition. In the following example, round
is a template declaration for a function
that rounds a number of type T
to
N
decimal places (see example 7-14
for the definition of round
), and
min
is a template definition for a
function that returns the minimum of two objects:
// Round off a floating-point value of type T to N digits. template<unsigned N, typename T> T round(T x); // Return the minimum of a and b. template<typename T> T min(T a, T b) { return a < b ? a : b; }
To use a function template, you must specify a template instance by providing arguments for each template parameter. You can do this explicitly, by listing arguments inside angle brackets:
long x = min<long>(10, 20);
However, it is more common to let the compiler deduce the template argument types from the types of the function arguments: ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.