我使用一个带有不同参数的函数的(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)
是否可以编写一个模板来为所有方法执行一次?
编辑:我的想法是避免每次使用它们时检查每个函数的结果.
你的意思是这样的吗?
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)