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 to double.

Even though every function template can be instantiated by specifying all its type ...

Get Hands-On Design Patterns with C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.