如何简化c ++中的多个if-else-if语句 [英] How to simplify multiple if-else-if statements in c++
本文介绍了如何简化c ++中的多个if-else-if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有四个函数用于四种情况:
Suppose I have four functions for four cases:
void ac() {
//do something
}
void ad() {
//do something
}
void bc() {
//do something
}
void bd() {
//do something
}
void f(bool a, bool b, bool c, bool d) {
if(a and c) {
ac();
}
else if(a and d) {
ad();
}
else if(b and c) {
bc();
}
else if(b and d){
bd();
}
else {
throw 1;
}
}
对于2乘2的情况来说很简单,在更复杂的情况下,
这可以得到非常乏味。是否有办法简化此操作?
For the 2 by 2 situation it's quite simple, but in more complex situations, this can get very tedious. Is there a way to simplify this?
推荐答案
#define A 0x1
#define B 0x2
#define C 0x4
#define D 0x8
void f(bool a, bool b, bool c, bool d) {
int mask = 0;
if( a ) mask |= A;
if( b ) mask |= B;
if( c ) mask |= C;
if( d ) mask |= D;
// Alternative is to use mask as a subscript in an array of function pointers.
switch( mask ) {
case A|C: ac(); break;
case A|D: ad(); break;
case B|C: bc(); break;
default: bd(); break;
}
}
这篇关于如何简化c ++中的多个if-else-if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文