Why does a C++ serializer branching on std::is_enum_v<T> compile with if constexpr but fail with a plain if?
answer
- every branch is instantiated
- discarded statement
- only inside a template
- the else-branch static_assert
basics
~20 sA plain if instantiates every branch for every T, so underlying_type_t<int> or value.size() on an enum is ill-formed. Inside a template, if constexpr (C++17) does not instantiate the discarded branch, so that code need only be valid for types reaching it.
solid answer
~40 sIn a function template, a plain `if (std::is_enum_v<T>)` is an ordinary run-time branch: the condition happens to be constant, but **both** branches are instantiated for every `T`, so `static_cast<std::underlying_type_t<T>>(value)` fails for `int` and `value.size()` fails for an enum. With `if constexpr` (C++17) the false branch is a **discarded statement**: during instantiation of the enclosing template it is not instantiated, so it may contain code that is invalid for this `T`. Three limits: the condition must be a constant expression; outside a template the discarded branch is still fully checked; and it must still parse. For the final `else`, `static_assert(false, "unsupported")` became valid in C++23 (CWG 2518, accepted as a defect report, and Apple clang 21 accepts it even in C++17 mode); older compilers need a dependent false such as `always_false<T>`.
code
cpp · 31 lines#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
template <class> inline constexpr bool always_false = false;
template <class T>
void write(std::vector<unsigned char>& out, const T& value) {
if constexpr (std::is_enum_v<T>) {
write(out, static_cast<std::underlying_type_t<T>>(value));
} else if constexpr (std::is_trivially_copyable_v<T>) {
const auto* p = reinterpret_cast<const unsigned char*>(&value);
out.insert(out.end(), p, p + sizeof(T));
} else if constexpr (std::is_same_v<T, std::string>) {
write(out, value.size());
out.insert(out.end(), value.begin(), value.end());
} else {
static_assert(always_false<T>, "write: unsupported type");
}
}
enum class Kind : unsigned char { ping = 1 };
int main() {
std::vector<unsigned char> buf;
write(buf, Kind::ping);
write(buf, 7);
write(buf, std::string("hi"));
std::cout << buf.size() << '\n'; // 1 + sizeof(int) + sizeof(std::size_t) + 2
}go deeper
Know that if constexpr exists since C++17 and that it lets one template contain code valid only for some types.
Explain instantiation versus execution: a plain if instantiates both branches, while if constexpr discards one inside a template; write the final static_assert correctly.
Know where the guarantee stops: non-template code, non-dependent names, helpers called from kept branches, branch order in a chain, and the C++23 static_assert change.
Judge when a long if constexpr chain should become a customization point or a set of overloads, so that new types can be supported without editing one central function.
## The plain if problem A generic serializer wants one `write` that handles enums, trivially copyable types and strings differently: ```cpp template <class T> void write(std::vector<unsigned char>& out, const T& value) { if (std::is_enum_v<T>) // plain if write(out, static_cast<std::underlying_type_t<T>>(value)); else if (std::is_same_v<T, std::string>) write(out, value.size()); // ... } ``` Calling `write(buf, Kind::ping)` fails even though the condition is a compile-time constant. A plain `if` is a run-time statement, and when the compiler **instantiates** `write<Kind>`, it instantiates **every** statement in the body. For `T = Kind`, `value.size()` is ill-formed; for `T = int`, `std::underlying_type_t<int>` names no type. Apple clang 21 reports `member reference base type 'const Kind' is not a structure or union` and, from libc++, `only enumeration types have underlying types`. ## if constexpr and discarded statements C++17 added `if constexpr (condition)`. The condition must be a contextually converted constant expression of type `bool`. If it is `false`, the first substatement is a **discarded statement**; if `true`, the `else` substatement is. The key rule: > During the instantiation of an enclosing templated entity, if the condition is not value-dependent after its instantiation, the discarded substatement is not instantiated. So for `T = Kind`, the string branch is never instantiated and `value.size()` is never checked. The serializer becomes: ```cpp if constexpr (std::is_enum_v<T>) { write(out, static_cast<std::underlying_type_t<T>>(value)); } else if constexpr (std::is_trivially_copyable_v<T>) { const auto* p = reinterpret_cast<const unsigned char*>(&value); out.insert(out.end(), p, p + sizeof(T)); } else if constexpr (std::is_same_v<T, std::string>) { write(out, value.size()); out.insert(out.end(), value.begin(), value.end()); } else { static_assert(always_false<T>, "write: unsupported type"); } ``` ## The final static_assert The `else` branch should reject anything unsupported at compile time. Its history: 1. A plain `static_assert(false, "...")` there was the obvious spelling, but before C++23 the rule "a template for which no valid specialization can be generated is ill-formed, no diagnostic required" applied to that substatement, so compilers rejected the template even when the branch was never used. 2. The workaround is a **dependent false**: `template <class> inline constexpr bool always_false = false;` and `static_assert(always_false<T>, "...")`. The compiler cannot evaluate it until `T` is known, so it only fires if the branch is instantiated. 3. C++23 changed the rule: a `static_assert` whose expression is evaluated in the context of a template definition has no effect, and failing static assertions are ignored when deciding whether a valid specialization exists. This was accepted as a **defect report** (CWG 2518), so compilers apply it to earlier modes as well; Apple clang 21 accepts `static_assert(false, ...)` in a discarded branch with `-std=c++17`. When a `std::vector<int>` reaches the `else`, the assertion fires: Apple clang 21 prints `static assertion failed due to requirement 'always_false<std::vector<int, std::allocator<int>>>': write: unsupported type`. ## Limits of if constexpr - **Only templates benefit.** In a non-template function, both branches are checked as usual; only odr-use rules relax, so a discarded branch may name an entity that is never defined. - **It is not `#if`.** The discarded branch must still be syntactically valid, and names that do not depend on `T` are still looked up. - **Return type deduction ignores discarded `return` statements**, so different branches of an `auto` function may return different types for different `T`. - **It does not cross function boundaries.** Calling a helper from a discarded branch avoids instantiating the call, but a helper called from a kept branch is instantiated in full. ## Branch order is priority An `if constexpr` chain takes the **first** condition that is true, and the traits overlap: every enum is also trivially copyable, and so are `int`, `double` and plain structs. The order of the chain is therefore the serializer's policy: 1. Put the **most specific** categories first (enums, then known class types such as `std::string`). 2. Put **broad** properties such as `std::is_trivially_copyable_v<T>` after them. 3. End with the rejecting `static_assert`. If the enum branch later starts writing a fixed-width wire integer instead of the in-memory representation, moving it below the trivially copyable branch would silently bypass it, and nothing would fail to compile. ## Replacing tag dispatch | Technique | Standard | Shape | |---|---|---| | tag dispatch | C++98 onward | overloads taking `std::true_type` / `std::false_type`, called with `Trait<T>{}` | | `if constexpr` | C++17 | one function, branches selected at instantiation | Tag dispatch scatters one decision over several overloads; `if constexpr` keeps the serializer's whole policy in one readable function.
- How did C++17 code write the final static_assert before the C++23 rule change?With a value that depends on the template parameter, such as `template <class> inline constexpr bool always_false = false;` and `static_assert(always_false<T>, "unsupported");`. Because the expression depends on `T`, it cannot be evaluated until the branch is instantiated for a specific type, so it fires only when an unsupported type actually reaches it.
- How does if constexpr interact with an auto return type?A deduced return type is computed only from the non-discarded `return` statements. A function such as `template <class T> auto to_wire(T v)` can return `std::underlying_type_t<T>` in an enum branch and `T` in another, and each instantiation gets the type of the branch it keeps.
- Can the condition of if constexpr test a function parameter's value?No. The condition must be a constant expression, and a function parameter is not one, even in a template. `if constexpr (n > 0)` with a parameter `n` is ill-formed; Apple clang 21 reports `constexpr if condition is not a constant expression`. Test types, traits, `sizeof` or template arguments instead, and use a plain `if` for run-time values.
- if constexpr skips the false branch even in a non-template function.
- A plain if with a constant condition behaves like if constexpr.
- The discarded branch need not parse, like code under #if 0.
- static_assert(false) in a discarded branch always fails, even in C++23.
- if constexpr makes the chosen branch execute at compile time.
Assumes C++17 for if constexpr; static_assert(false) in a discarded branch is the C++23 rule from CWG 2518, applied as a defect report to earlier modes.