Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 是否可以为枚举类枚举器别名?_C++_C++11_Enums_Alias_Language Lawyer - Fatal编程技术网

C++ 是否可以为枚举类枚举器别名?

C++ 是否可以为枚举类枚举器别名?,c++,c++11,enums,alias,language-lawyer,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 curre

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

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

使用声明中的枚举数 问题是,标准规定,在使用指定使用声明时,不应引用枚举类中的枚举数

7.3.3p7
使用
声明的
[namespace.udecl]
()

using声明不应命名作用域枚举器

注意
叮当声
不接受以上两行

引用枚举类本身的实际名称是完全正确的,但是试图引用它的一个枚举数是格式错误的

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

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

使用-和别名声明的替代方法 您可以声明一个常量,该常量具有您选择的任何名称,并使用您希望的值“alias”进行初始化:

int main(){
N::E value=x;//语义上等同于'value=N::E::A'`
}
排序:

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

使用红色=长的和丑陋的::颜色::红色这是类型别名的语法。我怀疑它很快会被用于任何其他用途。@dyp谢谢,你链接的页面回答了我的问题。关于你上次的评论,我记得g++也抱怨过这种形式,但我会尽快再试一次。实际上,你确定在使用long_和_丑陋::color编写
时,clang++会将所有枚举数“放入当前名称空间”吗@戴普,我很开心。它起作用了,因为我可以使用别名作为模板参数。也许还可以添加
constepr
和(在某些上下文中)
static
namespace long_and_ugly {
    enum class colour
    {
        red,
        green,
        blue
    };
}
const colour red = long_and_ugly::colour::red;