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:
The following code will oblige the compiler to instantiate two distinct functions: one squares the value and one cubes the value:
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 ...