std::is_constant_evaluated
Yields true when it called in a manifestly constant-evaluated expression or conversion.
That is roughly the case if we call it:
- in a constant-expression, or
- in a constant context (in 'if constexpr', a 'consteval function', or an 'constant initialization')
- for an initializer of a variable usable at compile time
When it makes no sense to use std::is_constant_evaluated()
As condition in a compile-time if, because that always yields true:
Inside a pure runtime function, because that usually yields false.
The only exception is if it is used in a local constant evaluation:
Inside a consteval function, because that always yields true:
Therefore, using std::is_constant_evaluated() usually only makes sense in constexpr functions.
std::is_constant_evaluated() and Operator ?: (conditional (ternary) operator)
Reasoning as follows:
- The initialization of sz1 and sz2 is either static initialization or dynamic initialization.
- For static initialization, the initializer must be constant. So, the compiler attempts to evaluate the initializer with std::is_constant_evaluated() treated as a constant of value true.
- With sz1, that succeeds. The result is 1, and that is a constant. So, sz1 is constant initialized with 20.
- With sz2, the result is sz, which is not a constant.
So, sz2 is (notionally) dynamically initialized. - Please refer to https://vsdmars.blogspot.com/2022/02/kernnelcc-ternary-conditional-operator.html as well as [ms doc] C++ Conditional Operator: ?:
- Rule of thumb; for ternary operator; both operands should have same type/value category; otherwise a conversion shall be triggered.
- Therefore, the previous result is discarded and the initializer is evaluated with std::is_constant_evaluated() producing false instead. So, the expression to initialize sz2 is also 20.
- However, sz2 is not necessarily a constant, because std::is_constant_evaluated() is not necessarily a constant-expression during this evaluation. So, the initialization of sz2 with this 20 does not compile.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.