...

/

Using constexpr if

Using constexpr if

Discover how constexpr if makes SFINAE easier after C++17 in this lesson.

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 ...