是否可以别名枚举-类枚举器
Is it possible to alias an enum-class enumerator?
给定一个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;
相关文章:
- 枚举类'classname'的多重定义
- typedef 枚举和枚举类有什么区别?
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 为什么 int 类型的枚举类值不能用作 int
- 在 C++ 中输出枚举类类型的向量元素
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么static_cast基础类型的枚举类int8_t获得意外值?
- C++ 使用枚举类对象分配 std::map 值
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- 枚举类的 C 样式强制转换到基础类型 char 的引用
- 枚举类的编译时索引器
- 如何将枚举类转发声明为模板化类的内部类?
- 我们应该如何使用枚举类进行索引(或者我们应该更好地避免这种情况)?
- 使用 Doxygen 记录枚举类值,而不启用EXTRACT_ALL
- 枚举类上的运算符+,起始值不为零
- C++:如何在声明枚举类的模板类主体之外定义枚举类?
- 创建结构作为枚举类成员
- 如何使用谷歌测试检查两个枚举类元素的相等性?
- 类与枚举类作为索引类型
- 如何通过索引访问枚举类