The compiler can decide whether or not enums are signed or unsigned.
Another method of validating enums is to use the enum itself as a variable type. For example:
enum Fruit
{
Apple = 0,
Banana,
Pineapple,
Orange,
Kumquat
};
enum Fruit fruitVariable = Banana; // Okay, Banana is a member of the Fruit enum
fruitVariable = 1; // Error, 1 is not a member of enum Fruit even though it has the same value as banana.
enum X : signed int { ... }; // signed enum
enum Y : unsigned int { ... }; // unsigned enum
不过,即使是现在,也可以通过使用枚举作为变量或参数类型来实现一些简单的验证,如下所示:
enum Fruit { Apple, Banana };
enum Fruit fruitVariable = Banana; // Okay, Banana is a member of the Fruit enum
fruitVariable = 1; // Error, 1 is not a member of enum Fruit
// even though it has the same value as banana.
7.2(6) : “对于 e (min)是最小枚举数,e (max)是最大的枚举数,枚举数的值是 b (min)到 b (max)范围内的底层类型的值,其中 b (min)和 b (max)分别是能存储 e (min)和 e (max)的最小位字段的最小和最大值。可以定义一个枚举,它的值不是由其任何枚举器定义的。”
例如:
enum { A = 1, B = 4};
defines an enumerated type where e(min) is 1 and e(max) is 4. If the underlying type is signed int, then the smallest required bitfield has 4 bits, and if ints in your implementation are two's complement then the valid range of the enum is -8 to 7. If the underlying type is unsigned, then it has 3 bits and the range is 0 to 7. Check your compiler documentation if you care (for example if you want to cast integral values other than enumerators to the enumerated type, then you need to know whether the value is in the range of the enumeration or not - if not the resulting enum value is unspecified).
这些值是否是函数的有效输入与它们是否是枚举类型的有效值可能是不同的问题。您的检查代码可能会担心前者,而不是后者,因此在本例中至少应该检查 > = A 和 < = B。
First off, C++03 Enum type is a distinct type of its own having no concept of sign. Since from C++03 standard dcl.enum
7.2 Enumeration declarations
5 Each enumeration defines a type that is different from all other types....
因此,当我们讨论一个枚举类型的符号时,比如当使用 <运算符比较两个枚举操作数时,我们实际上是在讨论隐式地将枚举类型转换为某种整数类型。It is the sign of this integral type that matters.在将枚举转换为整数类型时,应用下面的语句:
9 The value of an enumerator or an object of an enumeration type is converted to an integer by integral promotion (4.5).
而且,显然,枚举的基础类型与积分升级没有任何关系。因为标准是这样定义整体推广的:
4.5 Integral promotions conv.prom
.. An rvalue of an enumeration type (7.2) can be converted to an rvalue 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, or unsigned long.
因此,枚举类型是否成为 signed int或 unsigned int取决于 signed int是否可以包含所定义的枚举器的所有值,而不是枚举的底层类型。