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 ints, 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.
static_caston dereference?reinterpret_castwill work fine. It's using the resulting pointer that will not work.reinterpret_cast. timsong-cpp.github.io/cppwp/n4868/expr.reinterpret.cast#7?