...

/

Exploring Template Recursion

Exploring Template Recursion

Master the art of recursion and understand the recursive instantiation of templates.

In the “Variadic Templates” section, we discussed variadic templates and saw that they are implemented with a mechanism that looks like recursion. In fact, it’s overloaded functions and class template specializations, respectively. However, it’s possible to create recursive templates. To demonstrate how this works, we’ll look at implementing a compile-time version of the factorial function. This is typically implemented in a recursive manner, and a possible implementation is the following:

constexpr unsigned int factorial(unsigned int const n)
{
return n > 1 ? n * factorial(n - 1) : 1;
}
Possible implementation for finding factorials

This should be easy to understand: return the result of multiplying the function argument with the value returned by calling the function recursively with the decremented argument, or return the value 1 if the argument is 0 or 1. The type of the argument (and the return value) is unsigned int to avoid calling it for negative integers.

Recursion using class templates

To compute the value of the factorial function at compile-time, we need to define a class template that contains a data member holding the value of the function. ...