简体   繁体   中英

How to declare/define a function with the same return and parameter types as a given function pointer?

For example:

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.
}

I need to hook over 100 functions and copying and pasting is getting a bit tedious and adds a lot of bloat text.

Not sure exactly how you want to use it, but template can do a pretty good job here:

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
};

possibly static call might be replaced by operator () .

With usage as

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

For example:

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.
}

I need to hook over 100 functions and copying and pasting is getting a bit tedious and adds a lot of bloat text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM