是否可以代理任何功能

Flo*_*oFu 2 c++

我使用一个带有不同参数的函数的(C)库,但在出现错误时总是返回大于零的int:

int functionA(int param1, char param2); /* return an error code on failure, 0 otherwise */
int functionB(LIB_BOOLEAN param1);      /* return an error code on failure, 0 otherwise */
// ...
Run Code Online (Sandbox Code Playgroud)

我想将它们全部变为异常准备:

if (functionA(param1, param2) > 0)
{ throw std::runtime_error("Method failed"); }
Run Code Online (Sandbox Code Playgroud)

是否可以编写一个模板来为所有方法执行一次?

编辑:我的想法是避免每次使用它们时检查每个函数的结果.

sky*_*ack 6

你的意思是这样的吗?

template<typename F, typename... Args>
auto my_invoke(F &&f, Args&&... args) {
    if(std::forward<F>(f)(std::forward<Args>(args)...)) {
        throw std::runtime_error("Method failed");
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以称之为;

my_invoke(functionA, 0, 'c');
Run Code Online (Sandbox Code Playgroud)

  • @strep <疯狂的笑声> (3认同)
  • @streppel在这种情况下,它是一个_forwarding reference_.[Here](https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers)是一个很好的解释(使用_old_ name,_universal reference_). (3认同)