Template Creation
Learn how to create and customize templates with C++ using integers, specializations, and abbreviated functions.
Using integers as template parameters
Beyond general types, a template can also be of other types, such as integral types and floating-point types. In the following example, we will use an int in the template, which means that the compiler will generate a new function for every unique integer passed as a template argument:
template <int N, typename T>auto const_pow_n(const T& v) {auto product = T{1};for (int i = 0; i < N; ++i) {product *= v;}return product;}
The following code will oblige the compiler to instantiate two distinct functions: one squares the value and one cubes the value:
auto x2 = const_pow_n<2>(4.0f); // Squareauto x3 = const_pow_n<3>(4.0f); // Cube
Note the difference between the template parameter N
and the function parameter v
. For every value of N
, the compiler generates a new function. However, v
is passed as a regular parameter and, as such, does not result in a new function.
Providing specializations of a template
By default, the compiler will generate regular C++ code whenever we use a template with new parameters. But it’s also possible to provide a custom implementation for certain values of the template parameters. Say, for example, that we want to provide the regular C++ code of our const_pow_n()
function when it’s used with integers and the value of ...