Jean-Luc Nacif Coelho
Jean-Luc Nacif Coelho

Reputation: 1022

C++ - Function pointer with arbitrary number of args

I'm trying to make a CPP function that takes a function pointer and an arbitrary number of arguments, adds some coordinates, then calls the function pointer as such:

int func_api(void(*fun)(int, int, ...args), ...args) {
    fun(this.x, this.y, args);
}

so I can use it as such:

int func(int x, int y, int param1, int param2) {
    something;
}

int foo () {
    func_api(p1, p2);
}

Is there a way to do this?

Upvotes: 2

Views: 545

Answers (1)

Pradhan
Pradhan

Reputation: 16737

Use a variadic template

template <typename Func, typename ... Args>
int func_api(Func fun, Args&&... args)
{
 fun(this->x, this->y, std::forward<Args>(args)...);
}

You can now call it like this:

func_api(func, p1, p2);

Upvotes: 2

Related Questions