Detecting Constant Expressions in C 11
In C 11, it is possible to determine if an expression is a constant expression (constexpr) during compilation, which can be beneficial for optimizing code and ensuring certain properties.
Using noexcept(makeprval(e))
One way to determine if an expression is a constant expression is to use the following macro:
#define isprvalconstexpr(e) noexcept(makeprval(e))
where makeprval is a template function that takes a reference to an expression as input and returns a prvalue of the same type.
Explanation
The noexcept(e) expression returns false if e contains certain operations that are not allowed in constant expressions, such as non-throwing function calls, throw expressions, and throwable dynamic casts or typeids. If the call to makeprval is not a constant expression, the noexcept expression will also return false.
Limitations
While isprvalconstexpr is generally effective in detecting prvalue constant expressions, it has a subtle limitation. It may give false negatives in cases where an expression is a constant expression but contains potentially evaluated subexpressions that are not allowed in constant expressions.
Example Usage
The following example demonstrates the usage of isprvalconstexpr:
constexpr int a = (0 ? throw "fooled!" : 42); constexpr bool atest = isprvalconstexpr((0 ? throw "fooled!" : 42));
In this example, atest is false because the expression (0 ? throw "fooled!" : 42) is not a constant expression, even though the initialization of a is successful. This is because the "evil" non-constant subexpression throw "fooled!" is potentially evaluated, even though it is never actually evaluated in this specific case.
The above is the detailed content of Is My C 11 Expression a `constexpr`?. For more information, please follow other related articles on the PHP Chinese website!