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

To get the most out of this book

To get started with this book, you need to have some basic knowledge of the C++ programming language. You need to know the syntax and fundamentals about classes, functions, operators, function overloading, inheritance, virtual functions, and more. However, no knowledge of templates is required, as this book will teach you everything from scratch.

All the code samples in this book are cross-platform. That means you can use any compiler to build and run them. However, although many snippets work with a C++11 compiler, there are also snippets that require a C++17 or C++20 compliant compiler. Therefore, we recommend you use a compiler version that supports C++20 so you can run all the samples. The samples in this book have been tested with MSVC 19.30 (Visual Studio 2022), GCC 12.1/13, and Clang 13/14. If you don’t have such a C++20 compliant compiler on your machine, you can try one online. We recommend one of the following:

The C++ Insights online tools will be referred several times in the book for analyzing the code generated by the compiler.

You should refer to the page, https://en.cppreference.com/w/cpp/compiler_support, if you want to check compilers support for different versions of the C++ standard.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.