切换功能作为具有参数的参数

时间:2017-06-19 20:15:44

标签: c++

我想传递一个带有参数的回调函数:

class foo1{
    foo1(void (*callback)(float));
};
foo1::foo1(void (*callback)(float)){
    //excecute the callback at some point
}

float foo2(){
    return 1.1;
}
void foo3(float f){
    //do stuff with f
    return;
}
int main(){
    void (*p3)(float); 
//p3 is a pointer to a function that returns void and has a single float as input
    p3 = &foo3(foo2()); 
//p3 now points to foo3 wich fits the requirements. But it does not make sence to give that pointer an argument. 

    foo1(p3);
    return 0;
}

有几个错误和 我明白这不会有所作为。 (参见代码中的注释)但我不知道如何正确地做到这一点。我想传递一个函数作为回调,其输入值为foo2。

2 个答案:

答案 0 :(得分:1)

你可以使用lambda来做到这一点 这种方式应该有效:

struct foo1{
    template<typename F>
    foo1(F f) {
        //excecute the callback at some point
        f();
    }
};

float foo2(){
    return 1.1;
}

void foo3(float){
    //do stuff with f
    return;
}

int main(){
    foo1([param{foo2()}](){ foo3(param); });
}

考虑这个表达式:

[param{foo2()}](){ foo3(param); }

它创建一个类型为void(void)的可调用对象,这是你在foo2的第一个参数(右边?)处应用foo3执行结果所期望的。<登记/> 这就是为什么你可以在f()的构造函数中简单地将其作为foo1调用。

答案 1 :(得分:1)

你可以做更像这样的事情: class foo1 {     foo1(void(* callback)(float)); }; float foo2(); foo1 :: foo1(void(* callback)(float)){     //在某些时候执行回调     回调(foo2的()); } float foo2(){     返回1.1; } void foo3(float f){     //做f的东西 } int main(){     void(* p3)(float);     p3 =&amp; foo3;     foo1(P3);     //或者干脆:     // foo1(&amp; foo3);     返回0; } 如果你不希望foo1()将参数值传递给回调,那么不要使用输入参数来声明回调,使用另一个调用预期回调函数的回调函数: class foo1 {     foo1(void(* callback)()); }; foo1 :: foo1(void(* callback)()){     //在某些时候执行回调     打回来(); } float foo2(){     返回1.1; } void foo3(float f){     //做f的东西 } void foo4(){     foo3(foo2的()); } int main(){     void(* p4)();     p4 =&amp; foo4;     foo1(P4);     //或者干脆:     // foo1(&amp; foo4);     返回0; } 或者,在C ++ 11及更高版本中,您可以使用lambda: class foo1 {     模板&lt; class T&gt;     foo1(T回调){         //在某些时候执行回调         打回来();     } }; 要么: #include&lt; functional&gt; class foo1 {     foo1(std :: function&lt; void()&gt; callback){         //在某些时候执行回调         打回来();     } }; float foo2(){     返回1.1; } void foo3(float f){     //做f的东西 } int main(){     foo1([](){foo3(foo2());});     返回0; } 或者,您可以使用std :: bind(): class foo1 {     模板&lt; typename T&gt;     foo1(T回调){         //在某些时候执行回调         打回来();     } }; 要么: #include&lt; functional&gt; class foo1 {     foo1(std :: function&lt; void()&gt; callback){         //在某些时候执行回调         打回来();     } }; #include&lt; functional&gt; float foo2(){     返回1.1; } void foo3(float f){     //做f的东西 } int main(){     foo1(std :: bind(foo3,foo2()));     返回0; }
相关问题