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:
/* ... */
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With