一个函数参数中的c ++多个枚举使用按位或“|” [英] c++ multiple enums in one function argument using bitwise or "|"
问题描述
myFunction(One | Two);
由于我认为这是一个非常优雅的方式,我试图实现像我这样的东西:
void myFunction(int _a){
switch(_a){
case One:
cout< < !!!! << ENDL;
break;
案例二:
cout <<<< endl;
break;
}
}
现在,如果我尝试使用One |二,我想要两个交换机都被调用。我对二进制运算符不是很好,所以我真的不知道该怎么做。任何想法都会很棒!
谢谢!
你必须像这样的枚举:
枚举STATE {
STATE_A = 1,
STATE_B =
STATE_C = 4
};
ie。枚举元素值应为2,以选择有效案例或if语句。
所以当你这样做:
void foo(int state){
if(state& STATE_A){
// do something
}
if(state& STATE_B){
// do something
}
if(state& STATE_C){
// do东西
}
}
int main(){
foo(STATE_A | STATE_B | STATE_C);
}
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!
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);
}
这篇关于一个函数参数中的c ++多个枚举使用按位或“|”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!