【问题标题】:Is it possible to alias an enum-class enumerator?是否可以给枚举类枚举器起别名?
【发布时间】:2014-08-04 11:05:05
【问题描述】:

给定一个 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 red = long_and_ugly::colour::red; 这是类型别名的语法。我怀疑它很快就会被用于其他任何事情。
  • @dyp 谢谢,您链接的页面回答了我的问题。关于你最后的评论,我记得 g++ 也抱怨过那个表格,但无论如何我会尽快再试一次。
  • 其实,你确定clang++在写using long_and_ugly::colour;的时候把所有的枚举数都“放到了当前的命名空间”吗? The clang++ at coliru disagrees
  • @dyp 我很开心。它奏效了,因为我能够使用别名作为模板参数。

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


【解决方案1】:

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 确实接受上述两行; 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`
}

【讨论】:

    【解决方案2】:

    种类:

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

    【讨论】:

    • 也许还添加constexpr 和(在某些情况下)static。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多