DoubleX
DoubleX

Reputation: 371

C++: How to pass a function+arguments as parameter without executing it?

I have 3 algorithms function:

void algo1(int para1, int para2);
void algo2(int para1, int para2);
void algo3(int para1, int para2);

and I want set a timer to test these functions' efficiency

int get_execute_time( void(*f)(int para1, int para2) );

I pass the function as parameter to get_execute_time to avoid abundance, however, the problem is I also need to pass the arguments, which is para1, para2.

so I let timer function change to

get_execute_time( void(*f)(int para1, int para2) , 
                 int para1, int para2) {
    (*f)(para1, para2); // call it
}

and, the code above seems ugly to me, so is there any option to wrap the code and let the code execute later in C++?

so that I can do like this:

// definition
get_execute_time(this_code_will_execute_later) {
    this_code_will_execute_later();
};
// usage
get_execute_time(algo1(para1, para2));

Temporary solution: utilize class to implement closure-like thing( inspired from Do we have closures in C++?

class timer {
private:
    int para1;
    int para2;
public:
    timer(int para1, int para2);
    operator () (void(*f)(int para1, int para2)) { (*f)(para1, para2) }
}
// thus we can write these following code
timer timer(para1, para2);
std::cout << "run " << timer(algo1) << " ms";
std::cout << "run " << timer(algo2) << " ms"
std::cout << "run " << timer(algo3) << " ms"

So, Do exist better options? Thanks anyway!

Upvotes: 1

Views: 74

Answers (1)

catnip
catnip

Reputation: 25388

You can do this with either std::bind or via a lambda. For example (just one parameter shown for brevity):

#include <iostream>
#include <functional>

void get_execute_time (std::function <void (void)> f)
{
    f ();
}

void foo (int i)
{
    std::cout << i << '\n';
}

int main()
{
    int param = 42;
    auto f1 = std::bind (foo, param);
    get_execute_time (f1);

    ++param;
    auto f2 = [param] { foo (param); };
    get_execute_time (f2);
}

Output:

42
43

Live demo

Upvotes: 2

Related Questions