Defining Function Templates
Learn about the details of functional templates and how to detect their data types.
We'll cover the following...
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 course). This function does nothing more than add the two arguments and returns the result of this operation, which should have the same T
type.
Autodetection of data type
Function templates are only blueprints for creating actual functions and only exist in source code. Unless explicitly called in our source code, the function templates will not be present in the compiled executable. However, when the compiler encounters a call to a function template and ...