How to call a function several times in C++ with different parameters
c++, c++11, functional-programming
Solution
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;
}
Problem
I have the next code: ``` object a,b,c; fun (a); fun (b); fun (c); ``` I wonder if it is there any way to do something similar in C++98 or C++11 to: ``` call_fun_with (fun, a, b, c); ``` Thanks