Search⌘ K

Using constexpr if

Explore the use of constexpr if in C++17 to simplify template metaprogramming by enabling compile-time decisions. Understand how it replaces complex SFINAE techniques, reduces code complexity, and supports safer, more flexible conditional compilation in functions and templates.

Introduction to constexpr if

There’s a C++17 feature that makes SFINAE much easier. It’s called constexpr if, and it’s a compile-time version of the if statement. It helps replace complex template code with simpler versions. Let’s start by looking at a C++17 implementation of the serialize function that can uniformly serialize both widgets and gadgets:

template<typename T>
void serialize(std::ostream& os, T const& value)
{
if constexpr (uses_write_v<T>)
value.write(os);
else
os << value;
}
C++17 implementation of the serialize function

The syntax for constexpr if is if constexpr(condition). The condition must be a compile-time expression. There’s no short-circuit logic performed when evaluating the expression. This means that if the expression has the form a && b or a || b, then both a and b must be well formed.

constexpr if enables us to discard a branch at compile-time based on the value of the expression. In our example, when the ...