Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling template function pointer with variable argument number

Tags:

c++

templates

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

like image 586
Guilherme Bernal Avatar asked Jul 07 '11 17:07

Guilherme Bernal


1 Answers

C++0x variadic templates:

template<typename Func, typename... Args>
auto call(Func func, Args&&... args)
-> typename std::result_of<Func(Args...)>::type
{
    return func(std::forward<Args>(args)...);
}
like image 106
Luc Danton Avatar answered Nov 11 '22 05:11

Luc Danton