1

Given some enum or enum class, is it valid to convert either a reference or pointer to the underlying type of the enum, to a reference or pointer of the enum itself?

More concretely, is the following valid according to the C++ Standard:

#include <type_traits>

enum class Example : int { A, B };

int main()
{
    auto p = Example::A;

    // 'q' is the underlying type of 'Example'
    auto q = static_cast<std::underlying_type_t<Example>>(p);

    // Is this valid? Can 'r0' or 'r1' reference 'q' but projected as an 'Example'?
    auto& r0 = reinterpret_cast<Example&>(q);
    auto& r1 = *reinterpret_cast<Example*>(&q);
}

I don't really see any wording around references or pointers of integral values converted to references or pointers to enum types, so I'm uncertain here. The fact that static_cast rejects this code, requiring reinterpret_cast makes me suspect this is undefined behavior, or implementation-defined at best.


A little background:

My organization has noticed a lot of code-bloat due to containers with template types using strongly-typed enums. Normalizing these containers to integral instantiations has helped quite a bit, but doesn't preserve the type on the API -- so I would like to write some wrappers that do this for us.

Proxy reference-like-types could be used as well, but would break expressions like auto& x = y[z]. It would be convenient if it were possible to simply convert back-and-forth, since a delegation would be much simpler.

Human-Compiler
  • 11,022
  • 1
  • 32
  • 59

0 Answers0