Selecting branches at compile time with constexpr if
In the previous recipes, we saw how we can impose restrictions on types and functions using static_assert
and std::enable_if
and how these two are different. Template metaprogramming can become complicated and cluttered when we use SFINAE and std::enable_if
to define function overloads or when we write variadic function templates. A new feature of C++17 is intended to simplify such code; it is called constexpr if, and it defines an if
statement with a condition that is evaluated at compile time, resulting in the compiler selecting the body of a branch or another in the translation unit. Typical usage of constexpr if is for simplification of variadic templates and std::enable_if
-based code.
Getting ready
In this recipe, we will refer to and simplify the code written in two previous recipes. Before continuing with this recipe, you should take a moment to go back and review the code we have written in the previous recipes,...