Tim
Tim

Reputation: 7474

Calling functions with different number of parameters

I have multiple functions with different numbers of parameters, e.g.

double foo(double x, double y) { return x + y; }

double bar(double x, double y, double z) { return x + y + z; }

double zoo(double x, double y) { return x * y; }

I'd like to call the functions by their names using some catchall function in the following manner:

call_function("foo", x, y);
call_function("bar", x, y, z); 

It can be assumed that both parameters and function return have the same type (e.g. double as in the above example). Unfortunately due to complex nature of the project I cannot change the functions I call and I need to deal with them as-is.

Is there any simple solution for this?

Upvotes: 1

Views: 96

Answers (2)

Martin G
Martin G

Reputation: 18129

#define CALL(fn, x, y) fn(x, y)
#define CALL(fn, x, y, z) fn(x, y, z)

allows you to do:

CALL(foo, 13, 6);
CALL(bar, 1, 2, 3);

Would that be good enough?

Upvotes: 2

NiVeR
NiVeR

Reputation: 9806

I think what you are looking for is called overloading, that is the ability to declare the same method (same name) but with different number of parameters.

Upvotes: 0

Related Questions