简体   繁体   中英

Why can't C++11 strongly-typed enum be cast to underlying type via pointer?

In C++11 we can cast a strongly-typed enum ( enum class ) to its underlying type. But it seems we cannot cast a pointer to the same:

enum class MyEnum : int {};

int main()
{
  MyEnum me;

  int iv = static_cast<int>(me); // works
  int* ip = static_cast<int*>(&me); // "invalid static_cast"
}

I'm trying to understand why this should be: is there something about the enum mechanism that makes it hard or nonsensical to support this? Is it a simple oversight in the standard? Something else?

It seems to me that if an enum type is truly built on top of an integral type as above, we should be able to cast not only the values but also the pointers. We can still use reinterpret_cast<int*> or a C-style cast but that's a bigger hammer than I thought we'd need.

TL;DR: The designers of C++ don't like type punning.

Others have pointed out why it's not allowed by the standard; I will try to address why the writers of the standard might have made it that way. According to this proposal , the primary motivation for strongly-typed enums was type safety. Unfortunately, type safety means many things to many people. It's fair to assume consistency was another goal of the standards committee, so let's examine type safety in other relevant contexts of C++.

C++ type safety

In C++ in general, types are unrelated unless explicitly specified to be related (through inheritance). Consider this example:

class A
{
    double x;
    int y;
};

class B
{
    double x;
    int y;
};

void foo(A* a)
{
    B* b = static_cast<B*>(a); //error
}

Even though A and B have the exact same representation (the standard would even call them "standard-layout types"), you cannot convert between them without a reinterpret_cast . Similarly, this is also an error:

class C
{
public:
    int x;
};

void foo(C* c)
{
    int* intPtr = static_cast<int*>(c); //error
}

Even though we know the only thing in C is an int and you can freely access it, the static_cast fails. Why? It's not explicitly specified that these types are related. C++ was designed to support object-oriented programming, which provides a distinction between composition and inheritance. You can convert between types related by inheritance, but not those related by composition.

Based on the behavior you've seen, it's clear strongly-typed enums are related by composition to their underlying types. Why might this have been the model the standard committee chose?

Composition vs Inheritance

There are many articles on this issue better written than anything I could fit here, but I'll attempt to summarize. When to use composition vs. when to use inheritance is certainly a grey area, but there are many points in favor of composition in this case.

  1. Strongly-typed enums are not intended to be used as integral values. Thus the 'is-a' relationship indicated by inheritance does not fit.
  2. On the highest level, enums are meant to represent a set of discrete values. The fact that this is implemented through assigning an id number to each value is generally not important (unfortunately C exposes and thus enforces this relationship).
  3. Looking back at the proposal , the listed reason for allowing a specified underlying type is to specify the size and signedness of the enum. This is much more of an implementation detail than an essential part of the enum, again favoring composition.

You could argue for days about whether or not inheritance or composition is better in this case, but ultimately a decision had to be made and the behavior was modeled on composition.

Instead, look at it in a slightly different way. You can't static_cast a long* to int* even if int and long have identical underlying representations. For same same reason an enum based on int is yet treated as a unique, unrelated type to int and as such requires the reinterpret_cast .

An enumeration is a distinct type (3.9.2) with named constants. [...] Each enumeration defines a type that is different from all other types. [...] Two enumeration types are layout-compatible if they have the same underlying type.

[dcl.enum] (§7.2)

The underlying type specifies the layout of the enum in memory, not its relation to other types in the type system (as the standard says, it's a distinct type , a type of its own). A pointer to an enum : int {} can never implicitly convert to an int* , the same way that a pointer to a struct { int i; }; struct { int i; }; cannot, even though they all look the same in memory.

So why does the implicit conversion to int work in the first place?

For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type. [...] The value of an enumerator or an object of an unscoped enumeration type is converted to an integer by integral promotion (4.5).

[dcl.enum] (§7.2)

So we can assign values of an enum to an int because they are of type int . An object of enum type can be assigned to an int because of the rules of integer promotion. By the way, the standard here specifically points out that this is only true for C-style (unscoped) enums. This means that you still need the static_cast<int> in the first line of your example, but as soon as you turn the enum class : int into an enum : int it will work without the explicit cast. Still no luck with the pointer type though.

Integral promotions are defined in the standard at [conv.prom] (§4.5). I'll spare you the details of quoting the full section, but the important detail here is that all rules in there apply to prvalues of non-pointer types, so none of this applies to our little problem.

The final piece of the puzzle can be found in [expr.static.cast] (§5.2.9), which describes how static_cast works.

A value of a scoped enumeration type (7.2) can be explicitly converted to an integral type.

That explains why your cast from enum class to int works.

But note that all of the static_cast s allowed on pointer types (again, I won't quote the rather lengthy section) require some relationship between the types. If you remember the beginning of the answer, each enum is a distinct type, so there is no relationship to their underlying type or other enums of the same underlying type.

This ties in with @MarkB's answer : Static-casting a pointer enum to a pointer to int is analogous to casting a pointer from one integral type to another - even if both have the same memory layout underneath and values of one will implicitly convert to the other by the rules integral promotions, they are still unrelated types, so static_cast will not work here.

I think the error of thinking is that

enum class MyEnum : int {};

is not really inheritance. Of course you can say MyEnum is an int . However, it is different from classic inheritance, inasmuch as not all operations that are available on int s are available for MyEnum also.

Let's compare this to the following: A circle is an ellipse. However, it would almost always be wrong to implement a CirlceShape as inheriting from EllipseShape since not all operations that are possible on ellipses are also possible for circle. A simple example would be scaling the shape in x direction.

Hence, to think of enum classes as inheriting from an integer type leads to the confusion in your case. You cannot increment an instance of an enum class, but you can increment integers. Since it's not really inheritance, it makes sense to prohibit casting pointers to these types statically. The following line is not safe:

++*reinterpret_cast<int*>(&me);

This might be the reason why the committee prohibited static_cast in this case. In general reinterpret_cast is considered to be evil while static_cast is considered to be ok.

The answers to your questions can be found in the section 5.2.9 Static cast in the draft standard.

Support for allowing

int iv = static_cast<int>(me);

can be obtained from:

5.2.9/9 A value of a scoped enumeration type (7.2) can be explicitly converted to an integral type. The value is unchanged if the original value can be represented by the specified type. Otherwise, the resulting value is unspecified.

Support for allowing

me = static_cast<MyEnum>(100);

can be obtained from:

5.2.9/10 A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the resulting value is unspecified (and might not be in that range).

Support for not allowing

int* ip = static_cast<int*>(&me);

can be obtained from:

5.2.9/11 A prvalue of type “pointer to cv1 B,” where B is a class type, can be converted to a prvalue of type “pointer to cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The null pointer value (4.10) is converted to the null pointer value of the destination type. If the prvalue of type “pointer to cv1 B” points to a B that is actually a subobject of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

static_cast cannot be used to cast &me to an int* since MyEnum and int are not related by inheritance.

I think the reason for first static_cast is being able to work with functions and libraries that expect old style enum or even used a bunch of defined values for enumerations and directly expect an integral type. But there is no other logical relation between type enum and an integral type, so you should use reinterpret_cast if you want that cast. but if you have problems with reinterpret_cast you can use your own helper:

template< class EnumT >
typename std::enable_if<
    std::is_enum<EnumT>::value,
    typename std::underlying_type<EnumT>::type*
>::type enum_as_pointer(EnumT& e)
{
    return reinterpret_cast<typename std::underlying_type<EnumT>::type*>(&e);
}

or

template< class IntT, class EnumT >
IntT* static_enum_cast(EnumT* e, 
    typename std::enable_if<
        std::is_enum<EnumT>::value &&
        std::is_convertible<
            typename std::underlying_type<EnumT>::type*,
            IntT*
        >::value
    >::type** = nullptr)
{
    return reinterpret_cast<typename std::underlying_type<EnumT>::type*>(&e);
}

While this answer may not satisfy you about the reason of prohibiting static_cast of enum pointers , it give you a safe way to use reinterpret_cast with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM