c++ - 如何在 C++ 中使用不同的参数多次调用一个函数

标签 c++ c++11 functional-programming

我有下一个代码:

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/

相关文章:

c++ - CPP : Class as private member in another class

c++ - protected 成员变量的错误共享?

c++ - 将指向结构的指针转换为指向该结构的唯一成员的指针

c++ - 为什么成员 `float x` 在 main() 中为对象 `0.` 和 `a` 初始化为 `b`?

filter - 使用 Racket 构建过滤器内置函数

java - 如何使用 Collectors.summarizingInt 和 flatMap 运算符的用法来总结歌曲的投票

python - 如何在 python 的定义中引用一个不按名称的函数?

c++ - boost async_write 问题

c++ - 如何使用 cv::findcontours 和层次结构查找内孔数

c++11 - 避免 std::shuffle 中的自分配