【问题标题】:Final enum classes in C++11C++11 中的最终枚举类
【发布时间】:2016-08-30 09:12:20
【问题描述】:

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

考虑代码:

#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) 编译它可以工作...但是使用 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

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

【问题讨论】:

  • final 对枚举有什么影响?
  • enum class 文档也没有提到它。我怀疑这是一个编译器错误。
  • 另请注意,在 C++ 中,类不能从 char 等内置类型继承。
  • @Sergey 枚举类不同,底层类型始终是整型。

标签: c++ c++11 enums final


【解决方案1】:

final 说明符用于表示一个类不能被继承。由于无法继承 enum class,因此在您的情况下使用的 final 说明符是无用的。

来自here 的“Stollen”,并在 §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 起)。

因此,将带有 final 说明符的 enum class 定义为:

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

不是标准形式。

【讨论】:

  • 这也是我的想法......我只是好奇为什么 MSVS 启用它而不提及语法错误
  • @fritzone 可能在实施过程中误入歧途。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2023-03-30
相关资源
最近更新 更多