是否可以别名枚举-类枚举器

Is it possible to alias an enum-class enumerator?

本文关键字:枚举 -类 别名 是否      更新时间:2023-10-16

给定一个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;

但它也失败了。很抱歉没有粘贴错误。尽管如此,我相信你应该能够复制它。


问题(s)

  • 是否可以在标准c++ 11中声明枚举值的别名,或者我是否使用了clang扩展?

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

using-declarations中的枚举数

问题是标准规定,当使用using-declaration指定时,不能在enum类中引用枚举数。

7.3.3p7 using声明 [namespace.udecl] (n3337)

using-declaration

不能命名作用域枚举数。
namespace N {
  enum class E { A };
}
using N::E;    // legal
using N::E::A; // ill-formed, violation of [namespace.udecl]p7

注意: clang不接受以上两行;这是一个相关的bug报告。

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


别名中的枚举数-声明

标准规定别名声明只能用于引用类型名,因为枚举数不是类型,因此在这种上下文中使用枚举数是不正确的。

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

使用-

别名来替代 -声明

你可以声明一个常量,让你选择的任意名称用你想要的值初始化"别名":

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`
}

Sort of:

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