Home >Backend Development >C++ >Can We Determine if a C 11 Expression is `constexpr` at Compile Time Without Declarations?
Utilizing constexpr in C 11: Determining Constant Expressions
Question:
Is it feasible to ascercerain whether a C 11 expression qualifies as a constant expression (constexpr) during compile-time without relying on declarations?
Answer:
Utilizing the noexcept operator, it is possible to construct a compile-time boolean indicating whether an expression constitutes a constexpr:
template<typename T> constexpr typename remove_reference<T>::type makeprval(T&& t) { return t; } #define isprvalconstexpr(e) noexcept(makeprval(e))
Explanation:
The noexcept(e) expression validates the following conditions:
Limitations:
Due to the conservative nature of "potentially evaluated" expressions, there may be instances where noexcept may provide false negatives. For example:
constexpr int a = (0 ? throw "fooled!" : 42); constexpr bool atest = isprvalconstexpr((0 ? throw "fooled!" : 42)); // returns false
In this case, a is initialized successfully, but atest evaluates to false because the throw expression is potentially evaluated, even though it is never executed.
The above is the detailed content of Can We Determine if a C 11 Expression is `constexpr` at Compile Time Without Declarations?. For more information, please follow other related articles on the PHP Chinese website!