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)
Part 1: Core Template Concepts
Part 2: Advanced Template Features
Part 3: Applied Templates
Appendix: Closing Notes

Enabling SFINAE with the enable_if type trait

The C++ standard library is a family of sub-libraries. One of these is the type support library. This library defines types such as std::size_t, std::nullptr_t, and std::byte, run-time type identification support with classes such as std::type_info, as well as a collection of type traits. There are two categories of type traits:

  • Type traits that enable us to query properties of types at compile-time.
  • Type traits that enable us to perform type transformations at compile-time (such as adding or removing the const qualifier, or adding or removing pointer or reference from a type). These type traits are also called metafunctions.

One type trait from the second category is std::enable_if. This is used to enable SFINAE and remove candidates from a function’s overload set. A possible implementation is the following:

template<bool B, typename T = void>
struct enable_if {};
template<typename T>
struct enable_if...