Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More reliable value validness detection towards CWG1766 #398

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

frederick-vs-ja
Copy link

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 in bit_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 whether static_cast<E>(V) is a constant expression. When the answer is false, value V can't be an enumerator of E.

Rough test: https://godbolt.org/z/GbbW39MYP.

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 in `bit_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 whether `static_cast<E>(V)` is a constant expression. When
the answer is `false`, value `V` can't be an enumerator of `E`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant