Asserting Non-Occurrence of Constexpr if-else Clauses
In C , it is crucial to ensure that all constexpr if statements have at least one true branch. When none of the conditions are satisfied, a compile time error is desired to prevent unexpected behavior.
One common misconception is to employ static_assert(false) within the else clause. However, this approach is not accepted by the compiler.
To address this issue, the solution lies in making the discarded statement dependent on template parameters. By introducing a constexpr std::false_type class and specializing it with a template parameter T, we can create a condition that will always evaluate to false.
Here's an example:
template <class... T> constexpr std::false_type always_false{}; if constexpr (condition1) { ... } else if constexpr (condition2) { ... } else if constexpr (condition3) { ... } else { // Always false condition static_assert(always_false<T>); }
According to the C standard, section [temp.res]/8, if no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template, the program is considered ill-formed. This effectively ensures that the else clause is never taken and a compile time error is raised.
The above is the detailed content of How to Guarantee Compile-Time Errors for Unhandled Cases in C Constexpr if-else Statements?. For more information, please follow other related articles on the PHP Chinese website!