Search code examples
c++function-parameter

pass functions with different number of parameters to another function C++


Imagine a function func1 parameters of which are a function f and its arguments. Let there be two functions func2 and func3 which are supposed to be passed to func1 with the following definitions:

bool func2(int a, int b, float c){
    // does something with arguments and returns the boolean result
}

bool func3(int a, int b, float c, float d){
    // does something with arguments and returns the boolean result
}

I wonder how should I define func1 so that it can be compatible with both of these functions. Of course there is a turnaround and that is to pass a dummy parameter to func2 but this is not a good solution. I have read this post but it did not seem to be a compatible solution. Any ideas?

Edit:

This function is a C++ template which is meant to be equivalent to a python function like:

def func1(f, int a, int b, *args):
    if f(a, b, *args):
        # does something

Solution

  • Variadic templates can help you. The simplest version:

    template<class Fn, typename... Ts>
    void func1(Fn fn, int a, int b, Ts... args) {
        if (fn(a, b, args...))
            ...
    }
    
    func1(func2, 1, 2, 3);
    func1(func3, 1, 2, 3, 4);