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:
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: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.
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.