首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使代码更简洁

使代码更简洁
EN

Stack Overflow用户
提问于 2013-12-10 12:06:54
回答 6查看 589关注 0票数 5

如果这个问题不适合这样做,很抱歉。

我有一个C++函数,它近似于下面给出的MyFun()。

从这个函数中,我调用了一些(比如大约30个)返回布尔变量的其他函数(true表示成功,而false表示失败)。如果这些函数中的任何一个返回false,我也必须从MyFun()返回false。此外,如果中间函数调用失败,则不应该立即退出(不调用其余函数)。

目前,我正在按照下面给出的方式来处理这个问题,但是我觉得可能有一个更简洁的方法来处理这个问题。如有任何建议,将不胜感激。

非常感谢。

代码语言:javascript
复制
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;
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-12-10 12:19:32

使用类似于std::vector of std::function的东西。它的维护性要强得多。

示例:http://ideone.com/0voxRl

代码语言:javascript
复制
// 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。您将控制流与函数列表分离开来,在我看来,这是一件好事。

您可以通过使用一个名称为键的函数映射来改进这一点,该映射允许您输出哪个函数失败:

代码语言:javascript
复制
std::map<std::string, std::function<bool()>> function_map;
票数 11
EN

Stack Overflow用户

发布于 2013-12-10 12:11:08

我会将每个if语句替换为一个更顺滑的位数和赋值:

代码语言:javascript
复制
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;
}
票数 14
EN

Stack Overflow用户

发布于 2013-12-10 12:17:05

代码语言:javascript
复制
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;
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20494090

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档