对不起,如果这个问题不适合SO.
我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
HAL*_*000 14
我会if用一个更加符合的按位AND赋值替换每个语句:
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;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*han 11
使用有点像std::vector的std::function.它更加可维护.
// 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(); });
Run Code Online (Sandbox Code Playgroud)
如果要在函数失败时停止,则只需使用std::all_of而不是std::count_if.您将控制流与功能列表分离,这在我看来是一件好事.
您可以通过使用名称为键的函数映射来改进这一点,这将允许您输出哪个函数失败:
std::map<std::string, std::function<bool()>> function_map;
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
459 次 |
| 最近记录: |