Book Image

Template Metaprogramming with C++

By : Marius Bancila
5 (1)
Book Image

Template Metaprogramming with C++

5 (1)
By: Marius Bancila

Overview of this book

Learn how the metaprogramming technique enables you to create data structures and functions that allow computation to happen at compile time. With this book, you'll realize how templates help you avoid writing duplicate code and are key to creating generic libraries, such as the standard library or Boost, that can be used in a multitude of programs. The introductory chapters of this book will give you insights into the fundamentals of templates and metaprogramming. You'll then move on to practice writing complex templates and exploring advanced concepts such as template recursion, template argument deduction, forwarding references, type traits, and conditional compilation. Along the way, you'll learn how to write variadic templates and how to provide requirements to the template arguments with C++20 constraints and concepts. Finally, you'll apply your knowledge of C++ metaprogramming templates to implement various metaprogramming patterns and techniques. By the end of this book, you'll have learned how to write effective templates and implement metaprogramming in your everyday programming journey.
Table of Contents (16 chapters)
1
Part 1: Core Template Concepts
5
Part 2: Advanced Template Features
9
Part 3: Applied Templates
Appendix: Closing Notes

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.

...