C++ › Constexpr & Compile-Time

What is 'if constexpr' and why is it useful?

Advanced

Answer

if constexpr (C++17) is a compile-time conditional: only the taken branch is instantiated/compiled, and the other is discarded. It's invaluable in templates to select behavior based on type traits without needing separate overloads or SFINAE, keeping generic code readable while avoiding compilation of invalid branches.
template <class T>
auto value(T t) {
    if constexpr (std::is_pointer_v<T>) return *t;
    else return t;
}
Real-world example if constexpr lets one template function dereference pointers but return values directly for non-pointers.

Common follow-ups: How does it differ from a normal if? | Why does the untaken branch not compile?