1

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?

10
  • And the first parameter has to be a string like that? Commented Dec 3, 2016 at 20:51
  • 1
    You can just give them the same name or write wrapper functions for each of them and give the wrapper functions the same name. The compiler will call the right one based on the number of parameters you specify. Commented Dec 3, 2016 at 20:53
  • @Martin this would be preferable since it would be easiest for me just to be able to say "call the foo function" without bothering about anything else. Commented Dec 3, 2016 at 20:55
  • 1
    std::any and a map<std::string, std::function> Commented Dec 3, 2016 at 21:00
  • 1
    Then I am not sure how calling them with a string parameter differs from giving them unique names? Can you explain more about the problem you are trying to solve? Commented Dec 3, 2016 at 21:00

2 Answers 2

2
#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?

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

What you describe is called over loading, and not what the question is about i believe
You are right, but it seemed to me that the intention of the OP was to do something like this. I might be wrong though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.