How to call a function several times in C++ with different parameters
Here a variadic template solution.
#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 );
}
You may use the following using variadic template:
template <typename F, typename...Ts>
void fun(F f, Ts&&...args)
{
int dummy[] = {0, (f(std::forward<Ts>(args)), 0)...};
static_cast<void>(dummy); // remove warning for unused variable
}
or in C++17, with folding expression:
template <typename F, typename...Ts>
void fun(F&& f, Ts&&...args)
{
(static_cast<void>(f(std::forward<Ts>(args))), ...);
}
Now, test it:
void foo(int value) { std::cout << value << " "; }
int main(int argc, char *argv[])
{
fun(foo, 42, 53, 65);
return 0;
}
Using C++ 11, you can use std::function
, this way (which is quite quick to write IMO)
void call_fun_with(std::function<void(int)> fun, std::vector<int>& args){
for(int& arg : args){
fun(arg);
}
}
or, a bit more generic:
template<typename FTYPE>
void call_fun_with(FTYPE fun, std::vector<int>& args){
for(int& arg : args){
fun(arg);
}
}
Live example
Live example, templated version
Note: std::function
template arguments must be specified the following way: return_type(arg1_type, arg2_type,etc.)
EDIT: An alternative could be using std::for_each
which actually does pretty much the same thing, but which I do not really like as to the semantics, which are more like "for everything in this container, do...". But that's just me and my (maybe silly) way of coding :)