Defining Function Templates
Explore how to define function templates in C++ by using template parameters and the template keyword. Understand type deduction, explicit template arguments, and common errors when types are ambiguous or incompatible. Gain foundational knowledge for creating flexible functions and preparing for advanced template features.
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 is able to match the supplied ...