是否可以为枚举类枚举器添加别名?

问题描述 投票:0回答:2

给定一个 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 扩展?

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

c++ c++11 enums alias language-lawyer
2个回答
33
投票

使用声明中的枚举器

问题是标准规定,在使用指定

using-declaration 时,不应引用 enum 类中的枚举器。

7.3.3p7

 
using
声明
[namespace.udecl]
 (
n3337)

A

using-declaration 不得命名作用域枚举器。

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

注意clang

接受以上两行; 
这是相关的错误报告

引用

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


别名声明中的枚举器

标准规定,

别名声明

只能用于引用类型名称,因为枚举器不是一种类型,在这种情况下使用它是不正确的。 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-声明的替代方案 您可以声明一个常量,用您想要的“别名”值初始化您选择的任何名称:

namespace N { enum class E { A }; } constexpr N::E x = N::E::A;

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


5
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.