如何“退出当前函数,如果当前语句出错"在 C++ 中 [英] How to "exit current function, if error on current statement" in C++

查看:168
本文介绍了如何“退出当前函数,如果当前语句出错"在 C++ 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个例子开始阐述我的问题.并以问题的确切陈述作为结尾.

I start with an example to elaborate my problem. And conclude with the exact statement of the question at the end.

所以在C中,我们可以写一个这样的宏,

So in C, we can write a macro like this,

#define NO_ERROR 0
#define RETURN_IF_ERROR(function)                                       \
{                                                                       \
  RetCode = function;                                                   \
  if (RetCode != NO_ERROR)                                              \
  {                                                                     \
      LOG(ERROR,"[%d] line [%d] [%s]", RetCode, __LINE__, __FILE__ ) ); \
      return RetCode;                                                   \
  }                                                                     \
  else {                                                                \
      LOG(VERBOSE,"[%d] line [%d] [%s]", RetCode, __LINE__, __FILE__ ) );\
  }                                                                     \
}

现在这个宏可以用在这样的函数中了,

Now this macro could be used in a function like this,

int ConstructAxes() {
    RETURN_IF_ERROR(GetAxis("alpha"));
    RETURN_IF_ERROR(GetAxis("beta"));
    RETURN_IF_ERROR(GetAxis("gamma"));
    RETURN_IF_ERROR(GetAxis("delta"));
    .
    .
    .
}

因此,我们立即退出当前函数(例如 ConstructAxes)并返回错误代码,如果其中调用的函数之一返回错误.如果没有那个宏,对于这 4 个语句中的每一个,我都必须编写一个 if...else 块.我最终会得到 4 行代码来显示实际的功能或任务,然后是另外 16 行错误检查(和/或可选的日志记录).(我见过 700 多行长的函数,只有 20 到 30 行功能和 600 多行 if...else 错误检查和日志记录.那时不太容易遵循主要逻辑.)

So, we exit the current function (e.g. ConstructAxes) immediately with an error code, if one of the functions called within, returns with an error. Without that macro, for each of those 4 statements, I would have to write an if...else block. I'd end up with 4 lines of code that shows the actual functionality or task and then another 16 lines of error-checking (and/or optional logging). (I have seen functions which are 700+ lines long with only 20~30 lines of functionality and 600+ lines of if...else error checking and logging. Not very easy to follow the main logic then.)

(在任何人指出之前,我不能使用异常.这是一个遗留项目,不使用也不希望使用异常,我也不是编写异常安全代码的专家.此外,在任何人指出之前,返回的错误代码被重新解释为一些有意义的文本,在更高的层次上.哪里和如何与手头的这个问题无关.)

(p.s. before anyone points out, I cannot use exceptions. This is a legacy project and exceptions are not used and not desired to be used, nor am I an expert at writing exception-safe code. Also before anyone points out, the returned error code is reinterpreted into some meaningful text, at a higher level. Where and how is not relevant to this question at hand.)

问题是,宏可能有问题,我更喜欢函数.那么在不使用宏的情况下,是否有一些简洁优雅的方法可以在 C++ 中做到这一点?我觉得这是不可能的.

The question is, macros can be problematic and I'd prefer a function. So is there some clean&elegant way to do this in C++ without using a macro? I have a feeling it is NOT possible.

推荐答案

你可以写一个循环,比如:

You might write a loop, something like:

int RunFunctions(int line, // __LINE__
                 const char* file, // __FILE__
                 std::initializer_list<std::function<int()>> functions)
{
    int counter = 0;
    for (auto f : functions) {
        auto RetCode = f();

        if (RetCode != NO_ERROR) {
            LOG(ERROR,"[%d] line [%d] [%s] [%d]", RetCode, line, file, counter ));
            return RetCode;
        } else {
            LOG(VERBOSE,"[%d] line [%d] [%s] [%d]", RetCode, line, file, counter ) );
        }
        ++counter;
    }
    return NO_ERROR;
}

int ConstructAxes() {
    return RunFunctions(__LINE__, __FILE__, {
        []() { return GetAxis("alpha"); },
        []() { return GetAxis("beta"); },
        []() { return GetAxis("gamma"); },
        []() { return GetAxis("delta"); }
    });
}

直到我们有 std::source_location 或类似信息,__LINE____FILE__ 是必需的.

Until we have std::source_location or similar, __LINE__, __FILE__ would be required.

如果不需要捕获,可以通过函数指针改变std::function.

If you don't need capture, you may change std::function by function pointers.

这篇关于如何“退出当前函数,如果当前语句出错"在 C++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆