【发布时间】:2020-01-24 22:42:11
【问题描述】:
我想包装一些对现有 C 库的函数调用,该库调用该函数,检查是否设置了错误条件,然后返回函数的值(如果有)。 (具体来说,这适用于 OpenGL,但也适用于遗留的 C 函数。)由于函数可能返回 void ,这需要单独处理,这使情况变得复杂;并且由于我想抛出异常,这使我无法在保护对象超出范围时检查其析构函数。
以下代码基本有效:
void check_for_error() {
// check and handle legacy error messages
// if (errno != 0)
// if (glGetError() != GL_NO_ERROR)
// throw std::runtime_error{"suitable error message"};
}
template <class R, class... Args>
using RvalFunc = R(*)(Args...);
// specialisation for funcs which return a value
template <class R, class... Args>
R exec_and_check(RvalFunc<R, Args...> func, Args... args) {
R rval = func(std::forward<Args>(args)...);
check_for_error();
return rval;
}
template <class... Args>
using VoidFunc = void(*)(Args...);
// specialisation for funcs which return void - don't store rval
template <class... Args>
void exec_and_check(VoidFunc<Args...> func, Args... args) {
func(std::forward<Args>(args)...);
check_for_error();
}
示例用法:
exec_and_check(glBindBuffer, target, name);
FILE *pf = exec_and_check(fopen, "filename.txt", "rb");
...而不是...
glBindBuffer(target,name);
check_for_error();
FILE *pf = fopen("filename.txt", "rb");
check_for_error();
...检查可能会遗漏的地方,以及代码混乱的地方。我希望 R exec_and_check(RvalFunc<R, Args...> func, Args... args) 包含用于转发的通用引用(即 Args&&... args),但这种替换会导致编译错误 - Clang 给出了 note: candidate template ignored: deduced conflicting types for parameter 'Args' (<int, int> vs. <const int &, const int &>) 的示例。
如何修改此代码以接受通用引用?还是我遗漏了什么,有更好的方法来检查遗留代码?
【问题讨论】:
标签: c++ templates error-handling