1

I want to create a class, that will be implicitly convertible to selected enum classes, in order to switch over it. But following code does not compile (gcc). Compiler complains that conversion is ambiguous, but it does not compile with single conversion operator also (either one). How to implement such behaviour?

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;
    }
}
omicronns
  • 357
  • 1
  • 10

1 Answers1

1

Since you have two conversion operators, its quite ambiguous which to use withing the switch expression. You can explicitly convert it to the enum type of your choice using functional styled cast:

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

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

Demo

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
  • But the compiler knows that only one operator matches one switch, since removing one of operators removes one compiler error. – omicronns Mar 03 '17 at 14:24
  • 1
    @omicronns, of cause it "can" detect that. but, that will be a non-standard behavior. In your case, C++ requires the expression within the [`switch` statement](http://en.cppreference.com/w/cpp/language/switch) to be convertible to an enumeration type, the question, if you have two possible enumeration type, which enumeration type should the compiler take on? – WhiZTiM Mar 03 '17 at 14:32