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

Chapter 7: Patterns and Idioms

The previous parts of the book were designed to help you learn everything about templates, from the basics to the most advanced features, including the latest concepts and constraints from C++20. Now, it is time for us to put this knowledge to work and learn about various metaprogramming techniques. In this chapter, we will discuss the following topics:

  • Dynamic versus static polymorphism
  • The Curiously Recurring Template Pattern (CRTP)
  • Mixins
  • Type erasure
  • Tag dispatching
  • Expression templates
  • Typelists

By the end of the chapter, you will have a good understanding of various multiprogramming techniques that will help you solve a variety of problems.

Let’s start the chapter by discussing the two forms of polymorphism: dynamic and static.