Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ multiple enums in one function argument using bitwise or "|"

I recently came across some functions where you can pass multiple enums like this:

myFunction(One | Two);

Since I think this is a really elegant way I tried to implement something like that myself:

void myFunction(int _a){
    switch(_a){
        case One:
            cout<<"!!!!"<<endl;
            break;
        case Two:
            cout<<"?????"<<endl;
            break;
    }
}

now if I try to call the function with One | Two, I want that both switch cases get called. I am not really good with binary operators so I dont really know what to do. Any ideas would be great!

Thanks!

like image 290
moka Avatar asked Dec 09 '09 13:12

moka


2 Answers

For that you have to make enums like :

enum STATE {
  STATE_A = 1,
  STATE_B = 2,
  STATE_C = 4
};

i.e. enum element value should be in power of 2 to select valid case or if statement.

So when you do like:

void foo( int state) {

  if ( state & STATE_A ) {
    //  do something 
  }

  if ( state & STATE_B ) {
    //  do something 
  }

  if ( state & STATE_C ) {
    //  do something 
  }   
}

int main() {
  foo( STATE_A | STATE_B | STATE_C);
}
like image 179
Ashish Avatar answered Sep 19 '22 05:09

Ashish


Bitwise operators behave well only with powers of 2:

  0010
| 0100
------
  0110  // both bits are set


  0110
& 0100
------
  0100  // nonzero, i.e. true: the flag is set

If you try to do the same with arbitrary numbers, you'll get unexpected results:

  0101  // 5
| 1100  // 12
------
  1101  // 13

Which contains the possible (arbitrary) numbers as set flags: 0001 (1), 0100 (4), 0101 (5), 1000 (8), 1001 (9), 1100 (12), 1101 (13)

So instead of giving two options, you just gave six.

like image 35
György Andrasek Avatar answered Sep 20 '22 05:09

György Andrasek