why is the default type of enum class different than the underlying type of enum?

c++, c++11

Solution

As far as N4140 is concerned, MSVC is correct:

§7.2/5 Each enumeration defines a type that is different from all other types. Each enumeration also has an underlying type. The underlying type can be explicitly specified using an enum-base. For a scoped enumeration type, the underlying type is `int` if it is not explicitly specified. [...]

For rationale, you can read the proposal entitled Strongly Typed Enums (Revision 3) N2347. Namely, section 2.2.2 Predictable/specifiable type (notably signedness) explains that the underlying type of `enum` is implementation-defined. For example, N4140 again:

§7.2/7 For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than `int` unless the value of an enumerator cannot fit in an `int` or `unsigned int`. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value `0`.

And N2347's proposed solutions:

This proposal is in two parts, following the EWG direction to date:

• provide a distinct new enum type having all the features that are considered desirable:

o enumerators are in the scope of their enum

o enumerators and enums do not implicitly convert to int

o enums have a defined underlying type

• provide pure backward-compatible extensions for plain enums with a subset of those features

o the ability to specify the underlying type

o the ability to qualify an enumerator with the name of the enum

The proposed syntax and wording for the distinct new enum type is based on the C++/CLI [C++/CLI] syntax for this feature. The proposed syntax for extensions to existing enums is designed for similarity.

So they went with the solution to give scoped enums a defined underlying type.

Problem

I am asking why the following code yields an error in Visual Studio 2014 update 4. ``` enum A { a = 0xFFFFFFFF }; enum class B { b = 0xFFFFFFFF }; ``` I know that I can use `enum class B : unsigned int`. But why is the default underlying type of `enum` different that the default underlying type of `enum class`? There should be a design decision. Clarifications I forgot to mention the error: error C3434: enumerator value '4294967295' cannot be represented as 'int', value is '-1' That suggests that the default underlying type of `enum class` is `signed int` while the default type of `enum` is `unsigned int`. This question is about the sign part.

Original source

Related problems