给定一个 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-declaration 时,不应引用 enum 类中的枚举器。
7.3.3p7
using
声明[namespace.udecl]
(n3337)Ausing-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
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`
}
namespace long_and_ugly {
enum class colour
{
red,
green,
blue
};
}
const colour red = long_and_ugly::colour::red;