Why isn't this valid C++?:
enum foo : unsigned { first_foo, second_foo };
enum bar : foo { best_foo = first_foo };
GCC 5.4.0 says:
/tmp/a.cpp:3:16: error: underlying type ‘foo’ of ‘bar’ must be an integral type
enum bar : foo { best_foo = first_foo };
I can understand why I would get this error if foo
were a float
, or some struct, or what-not. But this seems perfectly legit to me in terms of semantics, type safety etc. What am I missing?
When you add things to C++, you tend to add the minimium amount that solves a problem.
The enum A:int
syntax lets you specify exactly how the enum A
is stored as an integer. That is all it does, and it solves the problem.
enum A:B
where B
is an enum could have many meanings. A
could extend B
, or A
could be a subset of the B
underlying type with different names, or A
could be an enum strictly restricted to have a subset of the values that can be stored within B
, or A
could be an enum whose values are restricted to the "hull" of B
values.
Of these, the "same underlying type" solution (with the :int
syntax) lines up with enum A:std::underlying_type_t<B>
. So there is already a way to do that, and it isn't particularly burdensome.
Until someone makes a suggestion for what enum A:B
should mean and convinces enough of the committee, it is unlikely to be permitted. And when there are multiple different reasonable meanings, this makes it harder for any one meaning to be chosen. One would need a strong use case why one particular meaning was best, and why it is worth the effort to put it in the standard.