C++11 中的最终枚举 类

Final enum classes in C++11

我只是好奇枚举 class 是否可以是最终的...因为编译器给我的结果是矛盾的。

考虑代码:

#include <iostream>

enum class some_enums final : char
{
    a = 'a', 
    b = 'b',
    c = 'c'
};

int main()
{
    some_enums aa = some_enums::a;
    std::cout << "aa=" << static_cast<char>(aa) << std::endl;
}

用 Visual Studio 2015 编译器 (http://rextester.com/l/cpp_online_compiler_visual) works... however compiling it with clang (http://rextester.com/l/cpp_online_compiler_clang) 编译它给我一个错误:

source_file.cpp:3:30: error: expected ';' after top level declarator
        enum class some_enums final : char

我在标准中的任何地方都没有看到最终枚举 classes 的踪迹,所以我相信 clang ... 但是为什么 Visual Studio 在这种情况下接受它,尽管它没有被提及在 MSDN (https://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx) ?

final 说明符用于表示 class 不能被继承。由于无法继承 enum class,因此在您的案例中使用的 final 说明符无用。

"Stollen" 来自 here 并在 §7.2/p1 枚举声明中提到 [dcl.enum]class enum 声明的形式为:

enum-key attr(optional) nested-name-specifier(optional) identifier enum-base(optional) ;
  • enum-key - enumenum class (C++11 起) 或 enum struct (C++11 起)之一
  • attr (C++11) - 任意数量属性的可选序列
  • identifier - 正在声明的枚举的名称。如果存在,并且如果此声明是重新声明,则它可以在 nested-name-specifier (C++11 起)之前:名称和作用域解析运算符的序列 ::,以作用域解析结束操作员。只有在无作用域的枚举声明中才能省略名称。
  • enum-base (C++11) - 冒号 (:),后跟一个 type-specifier-seq,它命名一个整数类型(如果是 cv-qualified,则忽略限定条件)。
  • enumerator-list - 以逗号分隔的枚举器定义列表,每个定义要么只是一个标识符,成为枚举器的名称,要么是一个带有初始值设定项的标识符:identifier = constexpr。在任何一种情况下,标识符后面都可以直接跟一个可选的属性说明符序列。 (C++17 起).

因此,将 enum classfinal 说明符定义为:

enum class some_enums final : char {
...
};

不是标准格式。