Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement and object implicit int conversion

Tags:

c++

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:
    /* ... */
    }
}
like image 859
James Magnus Avatar asked Jan 26 '23 05:01

James Magnus


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.

like image 107
Brian Bi Avatar answered Jan 28 '23 19:01

Brian Bi