Home  >  Article  >  Backend Development  >  How Does a Failed `static_assert` in an Untaken `if constexpr` Block Affect Program Validity?

How Does a Failed `static_assert` in an Untaken `if constexpr` Block Affect Program Validity?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 04:17:09722browse

How Does a Failed `static_assert` in an Untaken `if constexpr` Block Affect Program Validity?

How does a failed static_assert impact an if constexpr (false) block?

A static_assert within a non-taken branch of an if constexpr statement is deemed ill-formed, with no diagnostic required. This consequence stems from the rule in [temp.res]/8, which deems a program ill-formed if no valid specialization can be generated for a template or a substatement within a constexpr if statement.

In the case of static_assert, if the condition is nondependent and evaluates to false, no valid specialization can be generated for the template containing the assertion. This makes the program ill-formed, even if the branch is not taken.

However, static_asserts with a dependent condition remain unaffected. If the condition can evaluate to true for at least one type, the template remains valid.

Example

Consider the following code:

template< typename T><
constexpr void other_library_foo(){
    static_assert(std::is_same<T,int>::value);
}

template<class T>
void g() {
  if constexpr (false)
    other_library_foo<T>(); 
}

int main(){
    g<float>();
    g<int>();
}

Despite the if constexpr condition being false, the code is still ill-formed because the static_assert in other_library_foo contains a nondependent condition that evaluates to false.

The above is the detailed content of How Does a Failed `static_assert` in an Untaken `if constexpr` Block Affect Program Validity?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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