質問

I have an enum like (this is just an example):

enum tStates
{
    STOP            = (1<<0),
    PLAYING         = (1<<1),
    SYNCHRONISING       = (1<<2),
    READY_TO_PLAY       = (1<<3),
    CONNECTED       = (1<<4),
}

So it can be playing and connected at the same time etc... Multiple states at once is possible. I need to test different states, for instance:

if (m_pDeviceHealth->getHealth().isSet(PLAYING))
{


}
else if (m_pDeviceHealth->getHealth().isSet(STOP))
{


}

It tends to become quite big and difficult to read.

Is there a clearer way to check for a flag? Is it possible to use a switch for instance?

役に立ちましたか?

解決

Actually I don't know how the actual flag checking should be made simpler without your data structures or what you want to do with that. Basically what you have is:

if (m_pDeviceHealth->getHealth().isSet(PLAYING))
    | your expression           |      |your flag|

Seems quite minimal to me. For different flags you'll obviously need different if branches. If you are looking for checking if any of multiple bits is set, you can use bit masking like:

if (m_pDeviceHealth->getHealth() & (PLAYING | SYNCHRONIZING))

under the assumption that getHealth is an integer.

他のヒント

It's not nice but if you are looking for a switch, you can do flag combination yourself in cases:

switch (m_pDeviceHealth->getHealth().getValue()) {
   case PLAYING:
      // ...
      break;
   case STOP:
      // ...
      break;
   case CONNECTED:
   case SYNCHRONISING:
   case SYNCHRONISING|CONNECTED:
      // ...
      break;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top