我有下一个代码:
object a,b,c;
fun (a);
fun (b);
fun (c);
我想知道是否有任何方法可以在 C++98 或 C++11 中做类似的事情:
call_fun_with (fun, a, b, c);
谢谢
最佳答案
这里是可变模板解决方案。
#include <iostream>
template < typename f_>
void fun( f_&& f ) {}
template < typename f_, typename head_, typename... args_>
void fun( f_ f, head_&& head, args_&&... args) {
f( std::forward<head_>(head) );
fun( std::forward<f_>(f), std::forward<args_>(args)... );
}
void foo( int v ) {
std::cout << v << " ";
}
int main() {
int a{1}, b{2}, c{3};
fun(foo, a, b, c );
}
关于c++ - 如何在 C++ 中使用不同的参数多次调用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21454320/