Exploring template recursion
In Chapter 3, Variadic Templates, we discussed variadic templates and saw that they are implemented with a mechanism that looks like recursion. In fact, it is overloaded functions and class template specializations respectively. However, it is 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; }
This should be trivial 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.