Switch statement and object implicit int conversion

Viewed 155

In C++, is it legal / correct to use switch statement directly on an object which has an implicit conversion to int ? Instead of using a method returning the object tag.

class Action
{
  public:
    enum EType { action1, action2, action3};
    operator int() const { return mType; }
  private:
    EType mType;
  /* ... */
}

int main()
{
    Action a = /* ... */
    switch(a)
    {
    case Action::EType::action1:
        /* ... */
        break;
    case Action::EType::action2:
    /* ... */
    }
}
1 Answers

Yes, you can do that. See [stmt.switch]/2:

The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 7) to an integral or enumeration type.

Related