c++ - 是否可以给枚举类枚举器起别名?

标签 c++ c++11 enums alias language-lawyer

给定一个 C++11 枚举类,嵌套在几个长而丑陋的命名空间中:

namespace
    long_and_ugly
{
    enum class
        colour
    {
        red,
        green,
        blue
    };
}

可以为枚举值制作别名吗?使用 clang++ 3.5,可以执行以下操作:

using long_and_ugly::colour; // take all the values into the current namespace
using long_and_ugly::colour::red; // take only 'red' into the current namespace

function_taking_colour_argument( red ); // instead of fully referring to the value

g++ 4.9 然而,提示。我无法复制它的错误消息,因为我无法访问代码,但它明确提示 using 指令或声明的使用。我也试过这个:

using red = long_and_ugly::colour::red;

但它也失败了。很抱歉没有粘贴错误。不过,我相信您应该能够复制它。


问题

  • 是否可以在标准 C++11 中为枚举值声明别名,还是我使用了 clang 扩展?

  • 如果是,正确的语法是什么?

最佳答案

using-declarations 中的枚举数

问题在于,标准规定在使用指定 using-declaration 时,您不应在 enum 类 中引用枚举器。

7.3.3p7 The using declaration [namespace.udecl] (n3337)

A using-declaration shall not name a scoped enumerator.

namespace N {
  enum class E { A };
}

using N::E;    // legal
using N::E::A; // ill-formed, violation of [namespace.udecl]p7

注意:clang 确实接受上述两行; here's a relevant bug report .

引用 enum 类 本身的实际名称是完全可以的,但试图引用它的枚举器之一是不正确的。


别名声明中的枚举数

标准规定 alias-declaration 只能用于引用 type-name,因为 enumerator 不是一种类型,在这种情况下使用它是不正确的。

namespace N {
  enum class E { A };
}

using x = N::E;     // legal, `N::E` is a type
using y = N::E::A;  // ill-formed, `N::E::A` isn't a type

using-alias-declarations

的替代方案

您可以声明一个常量,该常量使用您希望“别名”的值初始化您选择的任何名称:

namespace N {
  enum class E { A };
}

constexpr N::E x = N::E::A;
int main () {
  N::E value = x; // semantically equivalent of `value = N::E::A`
}

关于c++ - 是否可以给枚举类枚举器起别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24212921/

相关文章:

c++ - 编译十六进制网格程序时错误代码C2768

c++11 - 复制但不移动

c++ - 使用模板化可变模板参数作为专用参数

c++ - 有什么比使用静态整数更好的存储信息的方法? C++

c++ - 指针和多维数组

c++ - 100 和 149 之间(包括)的随机数的固定范围

c++ - 设置文件指针位置

c++ - 主流 C++ 编译器中 GC 实现的时间表是什么?

java - Hibernate 异常 : java. lang.IllegalArgumentException:枚举类的未知名称值 []

python - 格式化的 Python 字符串既不使用 repr 也不使用 str - 发生了什么?