切换函数作为具有参数的参数

Handover function as parameter that has parameters

本文关键字:参数 函数      更新时间:2023-10-16

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

class foo1{
    foo1(void (*callback)(float));
};
foo1::foo1(void (*callback)(float)){
    //execute 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 which fits the requirements. But it does not make sense to give that pointer an argument. 
    
    foo1(p3);
    return 0;
}

有几个错误,我知道这没有意义。(请参阅代码中的注释(但我不知道如何正确地做到这一点。我想传递一个输入值为 foo2 的函数作为回调。

你可以做更多类似的事情:

class foo1 {
    foo1(void (*callback)(float));
};

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

float foo2() {
    return 1.1;
}
void foo3(float f) {
    //do stuff with f
}
int main() {
    void (*p3)(float); 
    p3 = &foo3; 
    foo1(p3);
    // or simply:
    // foo1(&foo3);
    return 0;
}

如果您不想foo1()将参数值传递给回调,则不要首先使用输入参数声明回调,请使用另一个调用预期回调函数的回调函数:

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

float foo2() {
    return 1.1;
}
void foo3(float f) {
    //do stuff with f
}
void foo4() {
    foo3(foo2());
}
int main() {
    void (*p4)(); 
    p4 = &foo4; 
    foo1(p4);
    // or simply:
    // foo1(&foo4);
    return 0;
}

或者,在 C++11 及更高版本中,您可以使用 lambda:

class foo1 {
    template<class T>
    foo1(T callback) {
        //excecute the callback at some point
        callback();
    }
};
Or:
#include <functional>
class foo1 {
    foo1(std::function<void()> callback) {
        //excecute the callback at some point
        callback();
    }
};

float foo2() {
    return 1.1;
}
void foo3(float f) {
    //do stuff with f
}
int main() {
    foo1([](){ foo3(foo2()); });
    return 0;
}

或者,您可以使用std::bind()

class foo1 {
    template <typename T>
    foo1(T callback) {
        //excecute the callback at some point
        callback();
    }
};
or:
#include <functional>
class foo1 {
    foo1(std::function<void()> callback) {
        //excecute the callback at some point
        callback();
    }
};

#include <functional>
float foo2() {
    return 1.1;
}
void foo3(float f) {
    //do stuff with f
}
int main() {
    foo1(std::bind(foo3, foo2()));
    return 0;
}

您可以使用 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) 的可调用对象,这是您在foo3的第一个参数处应用 foo2 执行结果所期望的(对吗?
这就是为什么您可以简单地在 foo1 的构造函数中将其作为f()调用。