6

新的 C++(C++0x 或 C++11)有一种新的枚举,一个“枚举类”,其中名称的范围为枚举(除其他外)。

enum class E {
    VAL1, VAL2
};

void fun() {
    E e = E::VAL1;  // Qualified name
}

但是,我想知道是否可以在某个范围内有选择地使用非限定名称。就像是:

void fun() {
    using E::*;
    E e = VAL1;
    switch (e) {
        case VAL2: ...

我看到我可以写using E::VAL1并得到一个值。但我不想对更大枚举的每个值都这样做。

4

2 回答 2

7

There is no way to do this in C++11. Just in case you are not aware of it - you get the E::Val1 notation even for an unscoped enumeration. For such an enumeration, you have Val1 accessible with and without the use of E::.

But you cannot take a scoped enumeration and selectively make all its enumerators visible in a given scope. It should also be noted that you can not write using E::Val1. The spec explicitly forbids this, your compiler just doesn't reject it yet.

于 2011-09-17T19:11:13.993 回答
1

这也是我碰巧想要的,但还没有尝试解决。这是一个未经测试的解决方案。编辑:我试过了,效果很好!这是我的第一个 C++11 实用程序宏。我还添加了一个过去的枚举器,以帮助将其扩展到“派生”枚举。

#define IMPORTABLE_ENUM( TYPENAME, ... ) \
\
struct import_ ## TYPENAME { \
    enum TYPENAME { \
        __VA_ARGS__ \
    }; \
}; \
\
typedef import_ ## TYPENAME :: TYPENAME TYPENAME;

这不能导入到块作用域中,但定义了一个基类import_duck以将枚举器带入一个类。用法:

IMPORTABLE_ENUM ( duck, huey, dewey, louie )

duck d = duck::dewey; // can't use unscoped enumerators here

struct duck_madness : private import_duck { // but inside a derived class
    duck who_did_it() { return huey; } // qualification is unnecessary
}

enum而且由于即使在派生类中也只有一种类型,所以static_cast不需要。

于 2011-09-17T21:26:38.937 回答