【问题标题】:How to declare/define a function with the same return and parameter types as a given function pointer?如何声明/定义具有与给定函数指针相同的返回和参数类型的函数?
【发布时间】:2021-01-25 02:51:56
【问题描述】:

例如:

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 多个函数,复制和粘贴变得有点乏味,并添加了很多臃肿的文本。

【问题讨论】:

  • 听起来像是一个相当简单的模板应用程序,而不是“宏”。这确实是 std::bind 所做的,但没有实际绑定任何参数。
  • "我需要挂钩 100 多个函数,而复制和粘贴变得有点乏味,并且会添加大量臃肿的文本。" 这听起来像是代码的工作-生成脚本。
  • @NicolBolas 这需要很长时间。单独查看 Windows 头文件是一场噩梦。
  • @JaMiT:这不会有帮助,因为函数的名称对他的用例非常重要。
  • @TonyClifton:“这需要很长时间。”为什么编写脚本需要很长时间?

标签: c++ templates function-pointers


【解决方案1】:

不确定你想如何使用它,但模板在这里可以做得很好:

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 () 替换。

使用 as

int a = 42, b = 51;
int res = Hook<&func>::call(a, b);

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 2021-07-03
    • 1970-01-01
    • 2018-07-05
    • 2013-03-16
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    相关资源
    最近更新 更多