使代码更清洁

Neo*_*low 5 c++

对不起,如果这个问题不适合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)

  • @egur:通过这里查看http://stackoverflow.com/questions/2488406/why-doesnt-c-have-or-for-booleans我改变主意,离开原来的答案. (2认同)
  • 我认为这个答案是完美的,并且使用按位和更有意义,特别是如果OP更喜欢将所有的&=语句合并为类似`Result&= AnotherFn1()&AnotherFn2()&AnotherFn3(); (2认同)

Joh*_*han 11

使用有点像std::vectorstd::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(); });
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)


dou*_*sin 5

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)