命名空间
变体
操作

枚举声明

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
通用主题
流程控制
条件执行语句
if
迭代语句(循环)
for
range-for (C++11)
跳转语句
函数
函数声明
Lambda 函数表达式
inline 说明符
动态异常规范 (在 C++17 中弃用*)
noexcept 说明符 (C++11)
异常
命名空间
类型
基本类型
枚举类型
函数类型
说明符
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
存储持续期说明符
初始化
 
 

枚举 是一种独特的类型,其值被限制在一个值范围内(详见下文),其中可能包括几个显式命名的常量(“枚举项”)。

常量的值是整数类型的值,称为枚举的底层类型。枚举具有与其底层类型相同的 大小值表示对齐要求。此外,枚举的每个值都具有与底层类型的相应值相同的表示。

枚举使用以下语法(重新)声明

enum-key attr (可选) enum-head-name (可选) enum-base (可选)
{ enumerator-list (可选) }
(1)
enum-key attr (可选) enum-head-name (可选) enum-base (可选)
{ enumerator-list , }
(2)
enum-key attr (可选) enum-head-name enum-base (可选) ; (3) (自 C++11 起)
1) enum-specifier,出现在 声明 语法的 decl-specifier-seq 中:定义枚举类型及其枚举项。
2) 尾随逗号可以跟随 enumerator-list
3) 不透明枚举声明:定义枚举类型但不定义其枚举项:在此声明之后,该类型是完整类型,并且其大小是已知的。
enum-key -

enum

(直到 C++11)

enumenum classenum struct 之一

(自 C++11 起)
attr - (自 C++11 起) 任意数量的 属性 的可选序列
enum-head-name -

正在声明的枚举的名称,可以省略。

(直到 C++11)

正在声明的枚举的名称,可以选择以 nested-name-specifier 为前缀:名称和作用域解析运算符 :: 的序列,以作用域解析运算符结尾。它只能在非作用域非不透明枚举声明中省略。
只有当枚举名称存在且此声明是重新声明时,nested-name-specifier 才可以出现。对于不透明枚举声明,nested-name-specifier 只能在 显式特化声明 中的枚举名称之前出现。
如果 nested-name-specifier 存在,则 enum-specifier 不能引用仅仅通过 using 声明 继承或引入的枚举,并且 enum-specifier 只能出现在封闭先前声明的命名空间中。在这种情况下,nested-name-specifier 不能以 decltype 说明符开头。

(自 C++11 起)
enum-base - (自 C++11 起) 冒号 (:),后跟一个 type-specifier-seq,该名称命名一个整数类型(如果它是 cv 限定的,则忽略限定),它将用作此枚举类型的固定底层类型
enumerator-list - 逗号分隔的枚举项定义列表,每个定义要么只是一个唯一的 identifier,它成为枚举项的名称,要么是一个带有常量表达式的唯一标识符:identifier = constant-expression在任何一种情况下,identifier 都可以直接后跟一个可选的 属性说明符序列(自 C++17 起)

枚举有两种不同的类型:非作用域枚举(使用 enum-key enum 声明)和 作用域枚举(使用 enum-key enum classenum struct 声明)。

内容

[编辑] 非作用域枚举

enum name (可选) { enumerator = constant-expression , enumerator = constant-expression , ... } (1)
enum name (可选) : type { enumerator = constant-expression , enumerator = constant-expression , ... } (2) (自 C++11 起)
enum name : type ; (3) (自 C++11 起)
1) 声明一个非作用域枚举类型,其底层类型未固定(在这种情况下,底层类型是实现定义的整数类型,可以表示所有枚举项值;除非枚举项的值无法容纳在 intunsigned int 中,否则此类型不大于 int。如果 enumerator-list 为空,则底层类型就像枚举具有单个枚举项且值为 0 一样。如果没有任何整数类型可以表示所有枚举项值,则枚举格式不正确)。
2) 声明一个非作用域枚举类型,其底层类型是固定的。
3) 非作用域枚举的不透明枚举声明必须指定名称和底层类型。

每个 enumerator 都会成为枚举类型(即 name)的命名常量,在封闭作用域中可见,并且可以在需要常量时使用。

enum Color { red, green, blue };
Color r = red;
 
switch(r)
{
    case red  : std::cout << "red\n";   break;
    case green: std::cout << "green\n"; break;
    case blue : std::cout << "blue\n";  break;
}

每个枚举项都与底层类型的值相关联。当在 enumerator-list 中提供 = 时,枚举项的值由那些关联的 constant-expression 定义。如果第一个枚举项没有 =,则关联的值为零。对于任何其他未定义 = 的枚举项,关联的值是上一个枚举项的值加一。

enum Foo { a, b, c = 10, d, e = 1, f, g = f + c };
//a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12

非作用域枚举的 name 可以省略:此类声明仅将枚举项引入封闭作用域

enum { a, b, c = 0, d = a + 2 }; // defines a = 0, b = 1, c = 0, d = 2

当非作用域枚举是类成员时,可以使用类成员访问运算符 .-> 访问其枚举项

struct X
{
    enum direction { left = 'l', right = 'r' };
};
X x;
X* p = &x;
 
int a = X::direction::left; // allowed only in C++11 and later
int b = X::left;
int c = x.left;
int d = p->left;

声明说明符成员声明 中,序列

enum enum-head-name :

始终被解析为枚举声明的一部分

struct S
{
    enum E1 : int {};
    enum E1 : int {}; // error: redeclaration of enumeration,
                      // NOT parsed as a zero-length bit-field of type enum E1
};
 
enum E2 { e1 };
 
void f()
{
    false ? new enum E2 : int(); // OK: 'int' is NOT parsed as the underlying type
}
(自 C++11 起)

[编辑] 用于链接目的的枚举名称

没有 用于链接目的的 typedef 名称 并且具有枚举项的未命名枚举,为了 链接目的,由其底层类型及其第一个枚举项表示; 这样的枚举被称为具有作为链接目的名称的枚举项。

[编辑] 作用域枚举

enum struct|class name { enumerator = constant-expression , enumerator = constant-expression , ... } (1)
enum struct|class name : type { enumerator = constant-expression , enumerator = constant-expression , ... } (2)
enum struct|class name ; (3)
enum struct|class name : type ; (4)
1) 声明一个作用域枚举类型,其底层类型为 int (关键字 classstruct 完全等效)
2) 声明一个作用域枚举类型,其底层类型为 type
3) 作用域枚举的不透明枚举声明,其底层类型为 int
4) 作用域枚举的不透明枚举声明,其底层类型为 type

每个 enumerator 都会成为枚举类型(即 name)的命名常量,它包含在枚举的作用域内,并且可以使用作用域解析运算符访问。作用域枚举器的值不会隐式转换为整数类型,尽管可以使用 static_cast 来获取枚举器的数值。

#include <iostream>
 
int main()
{
    enum class Color { red, green = 20, blue };
    Color r = Color::blue;
 
    switch(r)
    {
        case Color::red  : std::cout << "red\n";   break;
        case Color::green: std::cout << "green\n"; break;
        case Color::blue : std::cout << "blue\n";  break;
    }
 
    // int n = r; // error: no implicit conversion from scoped enum to int
    int n = static_cast<int>(r); // OK, n = 21
    std::cout << n << '\n'; // prints 21
}
(自 C++11 起)

如果以下所有条件都为真,则可以使用列表初始化从整数初始化枚举,而无需强制转换

  • 初始化是直接列表初始化。
  • 初始化列表只有一个元素。
  • 枚举是作用域枚举或具有固定底层类型的非作用域枚举。
  • 转换是非窄化的。

这使得引入新的整数类型(例如 SafeInt)成为可能,即使在惩罚按值传递/返回结构的 ABI 上,这些类型也享有与其底层整数类型相同的现有调用约定。

enum byte : unsigned char {}; // byte is a new integer type; see also std::byte (C++17)
byte b{42};        // OK as of C++17 (direct-list-initialization)
byte c = {42};     // error
byte d = byte{42}; // OK as of C++17; same value as b
byte e{-1};        // error
 
struct A { byte b; };
A a1 = {{42}};     // error (copy-list-initialization of a constructor parameter)
A a2 = {byte{42}}; // OK as of C++17
 
void f(byte);
f({42}); // error (copy-list-initialization of a function parameter)
 
enum class Handle : std::uint32_t { Invalid = 0 };
Handle h{42}; // OK as of C++17
(自 C++17 起)


using enum 声明

using enum using-enum-declarator ; (自 C++20 起)
声明符 - 一个(可能限定的)标识符简单模板标识符


declarator 必须命名一个非依赖枚举类型。枚举声明通过仅类型的普通限定非限定查找找到,具体取决于declarator是否被限定。

enum E { x };
 
void f()
{
    int E;
    using enum E; // OK
}
 
using F = E;
using enum F; // OK
 
template<class T>
using EE = T;
 
void g()
{
    using enum EE<E>; // OK
}

using enum 声明引入了命名枚举的枚举项名称,就像通过 using 声明 为每个枚举项一样。当在类作用域中时,using enum 声明将命名枚举的枚举项作为成员添加到作用域,使它们可用于成员查找。

enum class fruit { orange, apple };
 
struct S
{
    using enum fruit; // OK: introduces orange and apple into S
};
 
void f()
{
    S s;
    s.orange;  // OK: names fruit::orange
    S::orange; // OK: names fruit::orange
}

两个 using enum 声明引入了两个同名枚举项会冲突。

enum class fruit { orange, apple };
enum class color { red, orange };
 
void f()
{
    using enum fruit;    // OK
    // using enum color; // error: color::orange and fruit::orange conflict
}
(自 C++20 起)

[编辑] 注解

非作用域枚举类型的值可以提升转换为整数类型

enum color { red, yellow, green = 20, blue };
color col = red;
int n = blue; // n == 21

整数、浮点和枚举类型的值可以使用 static_cast 转换为任何枚举类型。请注意,此类转换后的值可能不一定等于为枚举定义的任何命名枚举项

enum access_t { read = 1, write = 2, exec = 4 }; // enumerators: 1, 2, 4 range: 0..7
access_t rwe = static_cast<access_t>(7);
assert((rwe & read) && (rwe & write) && (rwe & exec));
 
access_t x = static_cast<access_t>(8.0); // undefined behavior since CWG 1766
access_t y = static_cast<access_t>(8);   // undefined behavior since CWG 1766
 
enum foo { a = 0, b = UINT_MAX }; // range: [0, UINT_MAX]
foo x = foo(-1); // undefined behavior since CWG 1766,
                 // even if foo's underlying type is unsigned int
特性测试宏 Std 特性
__cpp_enumerator_attributes 201411L (C++17) 枚举项的属性
__cpp_using_enum 201907L (C++20) using enum

[编辑] 关键字

enum, struct, class, using

[编辑] 示例

#include <cstdint>
#include <iostream>
 
// enum that takes 16 bits
enum smallenum: std::int16_t
{
    a,
    b,
    c
};
 
// color may be red (value 0), yellow (value 1), green (value 20), or blue (value 21)
enum color
{
    red,
    yellow,
    green = 20,
    blue
};
 
// altitude may be altitude::high or altitude::low
enum class altitude: char
{
    high = 'h',
    low = 'l', // trailing comma only allowed after CWG 518
}; 
 
// the constant d is 0, the constant e is 1, the constant f is 3
enum
{
    d,
    e,
    f = e + 2
};
 
// enumeration types (both scoped and unscoped) can have overloaded operators
std::ostream& operator<<(std::ostream& os, color c)
{
    switch(c)
    {
        case red   : os << "red";    break;
        case yellow: os << "yellow"; break;
        case green : os << "green";  break;
        case blue  : os << "blue";   break;
        default    : os.setstate(std::ios_base::failbit);
    }
    return os;
}
 
std::ostream& operator<<(std::ostream& os, altitude al)
{
    return os << static_cast<char>(al);
}
 
// The scoped enum (C++11) can be partially emulated in earlier C++ revisions:
 
enum struct E11 { x, y }; // since C++11
 
struct E98 { enum { x, y }; }; // OK in pre-C++11
 
namespace N98 { enum { x, y }; } // OK in pre-C++11
 
struct S98 { static const int x = 0, y = 1; }; // OK in pre-C++11
 
void emu()
{
    std::cout << (static_cast<int>(E11::y) + E98::y + N98::y + S98::y) << '\n'; // 4
}
 
namespace cxx20
{
    enum class long_long_long_name { x, y };
 
    void using_enum_demo()
    {
        std::cout << "C++20 `using enum`: __cpp_using_enum == ";
        switch (auto rnd = []{return long_long_long_name::x;}; rnd())
        {
#if defined(__cpp_using_enum)
            using enum long_long_long_name;
            case x: std::cout << __cpp_using_enum << "; x\n"; break;
            case y: std::cout << __cpp_using_enum << "; y\n"; break;
#else
            case long_long_long_name::x: std::cout << "?; x\n"; break;
            case long_long_long_name::y: std::cout << "?; y\n"; break;
#endif
        }
    }
}
 
int main()
{
    color col = red;
    altitude a;
    a = altitude::low;
 
    std::cout << "col = " << col << '\n'
              << "a = "   << a   << '\n'
              << "f = "   << f   << '\n';
 
    cxx20::using_enum_demo();
}

可能的输出

col = red
a = l
f = 3
C++20 `using enum`: __cpp_using_enum == 201907; x

[编辑] 缺陷报告

以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。

DR 应用于 已发布行为 正确行为
CWG 377 C++98 当没有整数
类型可以表示所有枚举项值时,行为未指定
在这种情况下,枚举格式
不正确
CWG 518 C++98 在枚举项列表之后不允许尾随逗号 允许
CWG 1514 C++11 具有固定底层类型的枚举的重新定义
可以解析为类成员声明中的位域
始终解析为重新定义
CWG 1638 C++11 不透明枚举声明的语法
禁止用于模板特化
nested-name-specifier
允许
CWG 1766 C++98 将超出范围的值强制转换为枚举
没有固定底层类型的结果未指定
行为是未定义的
CWG 1966 C++11 CWG issue 1514 的解决方案使条件表达式的 :
成为 enum-base 的一部分
仅将解决方案应用于
成员声明说明符
CWG 2156 C++11 枚举定义可以通过 using-declarations 定义
枚举类型
禁止
CWG 2157 C++11 CWG issue 1966 的解决方案
未涵盖限定的枚举名称
已涵盖
CWG 2530 C++98 枚举项列表可能包含多个
具有相同标识符的枚举项
禁止
CWG 2590 C++98 枚举的大小、值表示和对齐要求
不取决于其底层类型
所有这些都与
底层类型的那些相同
CWG 2621 C++20 using enum 声明中使用的枚举名称查找不明确
已明确
CWG 2877 C++20 using enum 声明中使用的枚举名称查找不明确
using enum 声明不是仅类型
设为仅类型

[编辑] 参考

  • C++23 标准 (ISO/IEC 14882:2024)
  • 9.7.1 枚举声明 [dcl.enum]
  • C++20 标准 (ISO/IEC 14882:2020)
  • 9.7.1 枚举声明 [dcl.enum]
  • C++17 标准 (ISO/IEC 14882:2017)
  • 10.2 枚举声明 [dcl.enum]
  • C++14 标准 (ISO/IEC 14882:2014)
  • 7.2 枚举声明 [dcl.enum]
  • C++11 标准 (ISO/IEC 14882:2011)
  • 7.2 枚举声明 [dcl.enum]
  • C++03 标准 (ISO/IEC 14882:2003)
  • 7.2 枚举声明 [dcl.enum]
  • C++98 标准 (ISO/IEC 14882:1998)
  • 7.2 枚举声明 [dcl.enum]

[编辑] 参见

(C++11)
检查类型是否为枚举类型
(类模板) [编辑]
检查类型是否为作用域枚举类型
(类模板) [编辑]
获取给定枚举类型的底层整数类型
(类模板) [编辑]
将枚举转换为其底层类型
(函数模板) [编辑]
C 文档 关于 枚举