表达式中使用的枚举数是否与其枚举的基础类型具有相同的类型?

Does enumerator used in expression have the same type as underlying type of its enum?

枚举常量在无作用域枚举定义之外使用时的类型是什么?

考虑以下代码:

#include <iostream>

enum modes
{
    begin = 0,
    end = 1
};

int main()
{
    std::cout << std::boolalpha
        << std::is_same<unsigned int, typename std::underlying_type<modes>::type>::value
        << std::endl;
    std::cout << sizeof(modes) << std::endl;
    std::cout << (-100 + end) << std::endl;
}

这在我的机器上产生:

true
4
-99

现在,如果我只将其他一些枚举器的值 begin 更改为 2147483648,那么我的输出将变为:

true
4
4294967197

显然,这意味着 end 的类型已从 int 更改为 unsigned int,甚至 modes 的基础类型仍然相同(即 unsigned int).

关于枚举的整数提升是否有一些特殊规则?

来自 C++ 标准(7.2 枚举声明)

  1. ...Following the closing brace of an enum-specifier, each enumerator has the type of its enumeration....

还有(4.5积分促销)

3 A prvalue of an unscoped enumeration type whose underlying type is not fixed (7.2) can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration (i.e., the values in the range bmin to bmax as described in 7.2): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int. If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank (4.13) greater than the rank of long long in which all the values of the enumeration can be represented. If there are two such extended types, the signed one is chosen.

What is the type of enumeration constant, when it is used outside unscoped enum definition?

当然是枚举类型了。 begin 的类型是 modes。如果它有一个整型,你关于枚举的整型提升的问题就没有意义了。

Are there some special rules for integral promotions with enums?

不是真的。您正在考虑枚举的基础类型的整体提升,但这是不同的。对于枚举类型本身,需要考虑枚举类型的有效值范围,可以小于枚举底层类型的有效值范围。 int 可以表示所有有效值吗?如果是这样,你会得到一个 int