c++ - 如何声明/定义具有与给定函数指针相同的返回和参数类型的函数?
问题描述
例如:
int func(const int &i, const int &j);
// Want use pointer to func to do something along these lines.
func::return_type funcHook(func::parameters...)
// So I can have a macro to do this.
HOOK(func) {
// Do hook work.
}
我需要挂钩 100 多个函数,复制和粘贴变得有点乏味,并添加了很多臃肿的文本。
解决方案
不确定你想如何使用它,但模板在这里可以做得很好:
template <auto func> struct Hook;
template <typename Ret, typename ... Args, Ret (*func)(Args...)>
struct Hook
{
static Ret call(Args... args) {
// ...
// return func(std::forward<Args>(args)...);
}
};
// and handle also C-ellipsis as printf
template <typename Ret, typename ... Args, Ret (*func)(Args..., ...)>
struct Hook
{
#if 1
template <typename ...Us>
static Ret call(Args... args, Us&& ... ellipsis_args) {
// ...
// return func(std::forward<Args>(args)..., std::forward<Us>(ellipsis_args)...);
}
#else
static Ret call(Args... args, ...) {
// ...
// Cannot reuse func, as va_args should be used
}
#endif
};
可能static call
会被operator ()
.
用法为
int a = 42, b = 51;
int res = Hook<&func>::call(a, b);