Function templates are type agnostic function definitions which are used to create functions with actual types. These templates are used by compiler to generate overloaded functions based on the types of parameters passed while calling the function in the code.
This function template that used to create other functions is called primary template. Functions which are generated using this template are called instantiated functions.
It will be better to understand this with the help of an example. Let’s say we have a function min which usually can work with different types. One way that we can do is to overload min. However, it would be cumbersome to define multiple functions.
Other way we can use is function template as shown below.
T min(T a, T b)
{
return a < b ? a : b;
}Here, T can be of any type. T is called type template parameters or just template types.
Info
There is another kind of template parameter: non-type template parameters.
This is not enough for the compiler to create functions using this template. We need to tell the compiler that T is a template type and function definition is a template. We can do this using template keyword as shown below.
template <typename T>typename is used to specify that T is a template type.
So, the final example would look like,
#include <iostream>
template <typename T>
T min(T a, T b)
{
return a < b ? a : b;
}