C ++:如何将函数+参数作为参数传递而不执行它?

问题描述 投票:1回答:1

我有3个算法功能:

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

我想设置一个计时器来测试这些功能的效率

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

我将函数作为参数传递给get_execute_time以避免丰富,但问题是我还需要传递参数,即para1para2

所以我让计时器功能变为

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

并且,上面的代码对我来说似乎很难看,所以有没有选项来包装代码并让代码稍后在C ++中执行?

所以我可以这样做:

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

临时解决方案:利用class实现closure-like事物(灵感来自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"

那么,存在更好的选择吗?不管怎么说,还是要谢谢你!

c++ lambda closures
1个回答
2
投票

你可以用std::bind或lambda来做到这一点。例如(为简洁起见,只显示一个参数):

#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);
}

输出:

42
43

Live demo

© www.soinside.com 2019 - 2024. All rights reserved.