Athena
Athena

Reputation: 543

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

Upvotes: 1

Views: 3197

Answers (4)

Pickle Rick
Pickle Rick

Reputation: 808

Sounds like you want a variadic template. Something like this should be fine (on mobile so may be syntax errors).

template<typename TCallback, typename TArgs...>
void Func1(TCallback Evt, TArgs... Args)
{
    Evt(Args...);
}

void Func2(int Arg1, int Arg2) { }

Func1(Func2, 10, 100);

Upvotes: 1

Evg
Evg

Reputation: 26282

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

Upvotes: 4

Rohit Walavalkar
Rohit Walavalkar

Reputation: 818

I prefer a more readable code even if increases the number of lines one need to write.

Signature of func2 and func3 looks more of less similar. Hence you can make the func2 accept another default parameter like below

bool func2(int a, int b, float c, float d = 0){
    // 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
}

Now declare a function pointer and pass it to func1

bool (*fp) (int a, int b, float c, float d);

void func1(fp *fp1);

Please note that C++ doesn't really like function pointers

Upvotes: 1

Andrew
Andrew

Reputation: 447

I'm not 100% certain but I believe you should be creating a templatized function. Something like this.

template<typename T>
void func1 (T x, T y) {
    //code
}

Theoretically you should be able to substitute x and y with the bool from your function or whatever other values. Essentially you're creating your own custom type.

I've linked a reference below. Hope this helps.

https://en.cppreference.com/w/cpp/language/function_template

Upvotes: 0

Related Questions