枚举类(“新枚举”、“强枚举”)解决了传统 C++ 枚举的三个问题:
- 传统的
enums 隐式转换为int,当有人不希望枚举充当整数时会导致错误。
- 传统的
enums 将其枚举数导出到周围的作用域,导致名称冲突。
- 无法指定
enum 的底层类型,导致混淆、兼容性问题,并且无法进行前向声明。
enum class ("strong enums") 是强类型和作用域的:
enum Alert { green, yellow, orange, red }; // traditional enum
enum class Color { red, blue }; // scoped and strongly typed enum
// no export of enumerator names into enclosing scope
// no implicit conversion to int
enum class TrafficLight { red, yellow, green };
Alert a = 7; // error (as ever in C++)
Color c = 7; // error: no int->Color conversion
int a2 = red; // ok: Alert->int conversion
int a3 = Alert::red; // error in C++98; ok in C++11
int a4 = blue; // error: blue not in scope
int a5 = Color::blue; // error: not Color->int conversion
Color a6 = Color::blue; // ok
如图所示,传统枚举照常工作,但您现在可以选择使用枚举名称进行限定。
新的枚举是“枚举类”,因为它们将传统枚举(名称值)的各个方面与类的各个方面(作用域成员和不存在转换)结合在一起。
能够指定底层类型允许更简单的互操作性和有保证的枚举大小:
enum class Color : char { red, blue }; // compact representation
enum class TrafficLight { red, yellow, green }; // by default, the underlying type is int
enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U }; // how big is an E?
// (whatever the old rules say;
// i.e. "implementation defined")
enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U }; // now we can be specific
它还支持枚举的前向声明:
enum class Color_code : char; // (forward) declaration
void foobar(Color_code* p); // use of forward declaration
// ...
enum class Color_code : char { red, yellow, green, blue }; // definition
基础类型必须是有符号或无符号整数类型之一;默认为int。
在标准库中,enum 类用于:
- 映射系统特定错误代码:在
<system_error>:enum class errc;
- 指针安全指示器:在
<memory>:enum class pointer_safety { relaxed, preferred, strict };
- I/O 流错误:在
<iosfwd>:enum class io_errc { stream = 1 };
- 异步通信错误处理:在
<future>:enum class future_errc { broken_promise, future_already_retrieved, promise_already_satisfied };
其中有几个定义了运算符,例如==。