More reliable value validness detection towards CWG1766 #398
+25
−14
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
CWG1766 made out-of-range cast to enumeration without fixed underlying type raise undefined behavior. Such UB arguably also applies to
bit_cast
, although it's not required that UB inbit_cast
makes the expression non-constant.Currently, only Clang has implemented CWG1766, while Clang's underlying
__builtin_bit_cast
happens to be a workaround. However, it's more reliable to me to rely on the guarantee that core language UB causes constant evaluation failure.The approach in this patch effectively detects whether
std::integral_constant<E, static_cast<E>(V)>
is a valid type, which is equivalent to whetherstatic_cast<E>(V)
is a constant expression. When the answer isfalse
, valueV
can't be an enumerator ofE
.Rough test: https://godbolt.org/z/GbbW39MYP.