Home > Article > Backend Development > Why are `static_assert`s in the `false` branch of a `constexpr if` ill-formed?
constexpr if with Failed Static_Assert in the False Branch
Question:
Despite the proposal's lack of explicit mention of static_assert, why is its use within the non-taken branch of a constexpr if statement considered ill-formed?
Answer:
According to the rule for templates ([temp.res]/8), a program is ill-formed NDR (no diagnostic required) if:
In the case of a static_assert with a nondependent condition that evaluates to false, no valid specialization can be generated for the template containing the static_assert. Therefore, the program containing such a statement is ill-formed.
Example:
`
void f() {
if constexpr (false)
static_assert(false); // ill-formed
}
`
In this example, the static_assert in the non-taken branch of the constexpr if statement makes the entire function ill-formed, as no valid specialization can be generated for a template containing the static_assert.
However, this rule does not affect static_asserts with a dependent condition that can evaluate to true for at least one type.
The above is the detailed content of Why are `static_assert`s in the `false` branch of a `constexpr if` ill-formed?. For more information, please follow other related articles on the PHP Chinese website!