微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何声明/定义与给定函数指针具有相同返回和参数类型的函数?

如何解决如何声明/定义与给定函数指针具有相同返回和参数类型的函数?

例如:

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,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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。