Home > Backend Development > C++ > Why are `static_assert`s in the `false` branch of a `constexpr if` ill-formed?

Why are `static_assert`s in the `false` branch of a `constexpr if` ill-formed?

Mary-Kate Olsen
Release: 2024-11-25 11:59:11
Original
948 people have browsed it

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:

  • No valid specialization can be generated for a template, or a substatement of a constexpr if statement within a template.
  • The template is not instantiated.

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
Copy after login

}
`

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template