Template instantiations
The template name is not a type and cannot be used to declare a variable or call a function. To create a type or a function, the template must be instantiated. Most of the time, templates are instantiated implicitly when they are used. We will again start with function templates.
Function templates
To use a function template to generate a function, we have to specify which types should be used for all template type parameters. We can just specify the types directly:
template <typename T> T half(T x) { return x/2; } int i = half<int>(5);
This instantiates the half
function template with the int
type. The type is explicitly specified; we could call the function with an argument of another type, as long as it is convertible to the type we requested:
double x = half<double>(5);
Even though the argument is an int
, the instantiation is that of half<double>
, and the return type is double
. The integer value 5
is implicitly converted...