Calling template function pointer with variable argument number
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?
I开发者_StackOverflow中文版ntention:
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 t
s (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).
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)...);
}
Add another template variable:
template<typename T, typename U>
int call(T func, U a) { return func(a) }
template<typename T, typename U, typename V>
int call(T func, U a, V b) { return func(a,b) }
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
.
精彩评论