Reputation: 6609
Is there a legal way, according to the C++20 standard, to turn a pointer to an unscoped enumeration type's underlying type into a pointer to the enumeration type? In other words:
enum Enum : int {
FOO = 0,
BAR = 1,
}
// How do I implement this without undefined behavior (and ideally without
// implementation-defined behavior)?
const Enum* ToEnum(const int* p);
I'm surprised to find that it's not listed as a legal use of reinterpret_cast
.
If you're interested in why I want this: in a templated API I'm trying to work around the fact that protocol buffers provide repeated enum fields as a proto2::RepeatedField<int>
, i.e. an array of int
s, despite the fact that there is a strongly-typed enum associated with the field. I would like to be able to turn this into a std::span<Enum>
without needing to copy the values.
Upvotes: 1
Views: 203
Reputation: 39808
No, this is not one of the very few exceptions to the aliasing rule ([basic.lval]/11): you can construct such a std::span
, but attempting to use its elements (e.g., s.front()=FOO
) has undefined behavior.
Upvotes: 2