我想写一个函数,用它的参数调用另一个函数.看看我希望它如何工作:
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;
}
Run Code Online (Sandbox Code Playgroud)
预期产量:
3
42
5
Run Code Online (Sandbox Code Playgroud)
如何编写call函数(假设返回值始终相同)?我能想到的唯一方法就是这样:
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) }
Run Code Online (Sandbox Code Playgroud)
有没有办法用模板va_list或其他任何方法来解决这种重复?
意向:
它用于绘制几何图形,使用要绘制的参数方程解析函数.例:
Vector2i circle(float t, float radius) {
return Vector2i(cos(t * 2*PI) * radius, sin(t * 2*PI) * radius);
}
// ...
draw(circle, 10);
Run Code Online (Sandbox Code Playgroud)
该函数circle将在内部draw使用diferents ts(在0.0和之间1.0)多次调用.绘制的其他参数直接发送到函数,10将是radius.(Vector2i是一个自定义类).
Luc*_*ton 21
C++ 0x可变参数模板:
template<typename Func, typename... Args>
auto call(Func func, Args&&... args)
-> typename std::result_of<Func(Args...)>::type
{
return func(std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3069 次 |
| 最近记录: |