是否可以别名枚举类枚举器? [英] Is it possible to alias an enum-class enumerator?

查看:256
本文介绍了是否可以别名枚举类枚举器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given a C++11 enum class, nested inside several long- and ugly-named namespaces:

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

可以使用枚举值的别名吗?使用clang ++ 3.5,可以做如下:

Can aliases be made of the enumeration values? With clang++ 3.5, it is possible to do what follows:

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指令或声明。我也尝试过:

g++ 4.9, however, complains. I can't copy its error message because I can't access the code, but it explicitly complained about the usage of the using directive or declaration. I have also tried this:

using red = long_and_ugly::colour::red;

但它也失败了。很抱歉,没有粘贴错误。

But it also failed. I'm sorry for not pasting the errors. Nevertheless, I believe you should be able to reproduce it.


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

  • Is it possible to declare aliases to enumeration values in standard C++11, or was I using a clang extension?

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

If it is, what is the correct syntax?

推荐答案

中的枚举器

问题是,标准说你不应该引用一个枚举器使用指定 using-declaration 时,


7.3.3p7 / code>声明 [namespace.udecl] n3337


A using-declaration 不能为作用域的枚举器命名。

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 不接受上述两行; 这是一个相关的错误报告

Note: clang does accept both lines above; here's a relevant bug report.

参考枚举类本身的实际名称是完全正确的,但试图引用其中一个枚举器是错误的。

It's perfectly fine to refer to the actual name of the enum class itself, but trying to refer to one of its enumerators is ill-formed.

因为枚举器不是类型,所以别名声明只能用于引用 type-name 上下文是不成形的。

The standard says that an alias-declaration can only be used to refer to a type-name, since an enumerator isn't a type, using one in such context is ill-formed.

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值初始化的任何名字的常数:


Alternatives to using- and alias-declarations

You could declare a constant having whatever-name-of-your-choice initialized with the value you'd like to "alias":

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

这篇关于是否可以别名枚举类枚举器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆