C++ – Why Can’t an Enum Be the Underlying Type of Another Enum?

c++c++11enumssubclassing

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?

Best Answer

C++11 [dcl.enum]/2:

The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored.

Enums are not themselves integral types – [basic.fundamental]/7:

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.

This is accompanied by a non-normative footnote:

Therefore, enumerations are not integral; however, enumerations can be promoted to integral types as specified in [conv.prom].

To achieve the effect I think you're looking for, however, is still simple:

enum bar : std::underlying_type<foo>::type { best_foo = first_foo };
Related Question