我使用一个 (C) 库,其中的函数采用不同的参数,但在出现错误时总是返回一个大于零的整数:
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 */
// ...
我想把它们都变成异常准备:
if (functionA(param1, param2) > 0)
{ throw std::runtime_error("Method failed"); }
是否可以编写一个模板来为所有方法做一次?
编辑: 我的想法是避免每次使用时都检查每个函数的结果。
最佳答案
你的意思是这样的吗?
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");
}
}
你可以这样调用它;
my_invoke(functionA, 0, 'c');
关于c++ - 是否可以代理任何功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904526/