Alex Rivera | Logout

Calling template function pointer with variable argument number

Asked 2011-07-07T17:03:09.193
11

I want to write a function that calls another function with its arguments. See how I want that it work:

int sum(int a, int b) { return a + b }
int succ(int a)       { return a + 1 }
int size(char* str)   { return strlen(str) }

int call(???) { ??? }

int main() {
  cout << call(sum, 1, 2) << endl;
  cout << call(succ, 41) << endl;
  cout << call(size, "teste") << endl;
}

Expected output:

3
42
5

How can I write the call function (assuming that the return value is always the same)? The only way that I can think is this:

template<typename T> int call(T func, int a, int b) { return func(a, b) } 
template<typename T> int call(T func, int a)        { return func(a) } 
template<typename T> int call(T func, char* a)      { return func(a) } 

Is there any way to solve this repetition with templates, va_list or anything else?

Intention:

It's for drawing geometry pictures, parsing a function with the parametric equation to be drawed. Example:

Vector2i circle(float t, float radius) {
  return Vector2i(cos(t * 2*PI) * radius, sin(t * 2*PI) * radius);
}
// ...
draw(circle, 10);

The function circle will be called many times inside draw with diferents ts (between 0.0 and 1.0). The others arguments of draw is sent directly to the funcions, 10 will be radius. (Vector2i is a custom class).

Edit
Report

1 Answer

2

How about a simple #define for current C++ solution:

#define call(FUNC, ...) FUNC(__VA_ARGS__)

Here is the demo. I would advise to use a better name then a generic name like call as you are using #define.

answered 2011-07-08T03:18:36.223

Your Answer