自定义 class 到枚举 classes 的隐式转换

Implicit convertion of custom class to enum classes

我想创建一个 class,它可以隐式转换为选定的枚举 classes,以便切换它。但是以下代码无法编译(gcc)。编译器抱怨转换不明确,但它也不会使用单个转换运算符(任何一个)进行编译。如何实现这种行为?

enum class G : int {
    A,
    B = 0x100,
};

enum class B : int {
    B1 = 0x100,
    B2
};

struct Foo {
    int s;

    operator G() {
        return static_cast<G>(s & ~0xff);
    }

    operator B() {
        return static_cast<B>(s);
    }
};

void foo() {
    Foo s;
    s.s = static_cast<int>(B::B1);

    switch (s) {
        case G::A:
            break;
        default:
            break;
    }

    switch (s) {
        case B::B1:
            break;
        default:
            break;
    }
}

由于您有两个转换运算符,因此在 switch 表达式中使用哪个运算符非常不明确。您可以使用 functional styled cast:

将其显式转换为您选择的 enum 类型
switch (G(s)) {
    case G::A:
        break;
    default:
        break;
}

switch (B(s)) {
    case B::B1:
        break;
    default:
        break;
}

Demo