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:

Get hands-on with 1400+ tech skills courses.