1

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.

4
  • Could create a borrowed range that does a static_cast on dereference? Commented Oct 23, 2022 at 23:57
  • reinterpret_cast will work fine. It's using the resulting pointer that will not work. Commented Oct 24, 2022 at 0:05
  • I'm surprised to find that it's not listed as a legal use of reinterpret_cast. timsong-cpp.github.io/cppwp/n4868/expr.reinterpret.cast#7? Commented Oct 24, 2022 at 8:57
  • Thank you language lawyer tag inhabitants for your pedantry, which is exactly what I'm after. :-) Yes, what I mean is that I want to be able to obtain a pointer and then actually be able to dereference it. Commented Oct 25, 2022 at 0:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.