Using constexpr if
A C++17 feature 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; }
The syntax for constexpr if
is if constexpr(condition)
. The condition must be a compile-time expression. There is 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...