Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function several times in C++ with different parameters

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

like image 557
Vicente Bolea Avatar asked Jan 30 '14 10:01

Vicente Bolea


People also ask

Can a function be called multiple times in C?

We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How do you call the same function multiple times?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

How many times can you call a function in C?

This is where the answer to your question comes in. Because the source code of the script is in memory, we can call its functions as often as we wish. We can even keep running variables, as long as they are not re-defined.

How do you call a function a certain number of times?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.


2 Answers

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 );
}
like image 129
galop1n Avatar answered Oct 28 '22 06:10

galop1n


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;
}
like image 44
Jarod42 Avatar answered Oct 28 '22 04:10

Jarod42