如果这个问题不适合这样做,很抱歉。
我有一个C++函数,它近似于下面给出的MyFun()。
从这个函数中,我调用了一些(比如大约30个)返回布尔变量的其他函数(true表示成功,而false表示失败)。如果这些函数中的任何一个返回false,我也必须从MyFun()返回false。此外,如果中间函数调用失败,则不应该立即退出(不调用其余函数)。
目前,我正在按照下面给出的方式来处理这个问题,但是我觉得可能有一个更简洁的方法来处理这个问题。如有任何建议,将不胜感激。
非常感谢。
bool MyFun() // fn that returns false on failure
{
bool Result = true;
if (false == AnotherFn1()) // Another fn that returns false on failure
{
Result = false;
}
if (false == AnotherFn2()) // Another fn that returns false on failure
{
Result = false;
}
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}发布于 2013-12-10 12:19:32
使用类似于std::vector of std::function的东西。它的维护性要强得多。
示例:http://ideone.com/0voxRl
// List all the function you want to evaluate
std::vector<std::function<bool()>> functions = {
my_func1,
my_func2,
my_func3,
my_func4
};
// Evaluate all the function returning the number of function that did fail.
unsigned long failure =
std::count_if(functions.begin(), functions.end(),
[](const std::function<bool()>& function) { return !function(); });如果要在函数失败时停止,只需使用std::all_of而不是std::count_if。您将控制流与函数列表分离开来,在我看来,这是一件好事。
您可以通过使用一个名称为键的函数映射来改进这一点,该映射允许您输出哪个函数失败:
std::map<std::string, std::function<bool()>> function_map;发布于 2013-12-10 12:11:08
我会将每个if语句替换为一个更顺滑的位数和赋值:
bool MyFun() // fn that returns false on failure
{
bool Result = true;
Result &= AnotherFn1(); // Another fn that returns false on failure
Result &= AnotherFn2(); // Another fn that returns false on failure
// Repeat this a number of times.
.
.
.
if (false == Result)
{
cout << "Some function call failed";
}
return Result;
}发布于 2013-12-10 12:17:05
bool MyFun() // fn that returns false on failure
{
bool Result = true;
// if need to call every function, despite of the Result of the previous
Result = AnotherFn1() && Result;
Result = AnotherFn2() && Result;
// if need to avoid calling any other function after some failure
Result = Result && AnotherFn1();
Result = Result && AnotherFn2();
return Result;
}https://stackoverflow.com/questions/20494090
复制相似问题