【发布时间】:2015-12-24 00:21:09
【问题描述】:
有没有一种方法可以在多个条件下分支而不编写看起来像一团糟的代码? C++11 或 C++14 中的语法糖将不胜感激。
#include <iostream>
enum state
{
STATE_1,
STATE_2,
STATE_3,
STATE_4,
STATE_5,
STATE_6,
STATE_7,
STATE_8,
};
state f(int a, bool b, const std::string& str)
{
// How not to:
if (a < 0)
{
if (b == false)
{
if (str != "morning")
{
return STATE_1;
}
else
{
return STATE_2;
}
}
else
{
if (str != "morning")
{
return STATE_3;
}
else
{
return STATE_4;
}
}
}
else // a >= 0
{
if (b == false)
{
if (str != "morning")
{
return STATE_5;
}
else
{
return STATE_6;
}
}
else
{
if (str != "morning")
{
return STATE_7;
}
else
{
return STATE_8;
}
}
}
}
int main()
{
std::cout << "State: " << f(1, true, "morning") << std::endl;
}
【问题讨论】: