在C++中将函数传递给类

beg*_*neR 0 c++ function-pointers function std-function

我想在一个类中存储一个函数,只需在一个成员函数中调用该函数.我知道这可以使用函数指针,但我想用std::function它.

以下是一些不起作用的代码,但应该演示我想要做的事情:

double foo(double a, double b){
    return a + b;
}


class Test{
 private:
        std::function<double(double,double)> foo_ ;
 public:
        Test(foo);
        void setFoo(foo) {foo_ = foo;}
        double callFoo(double a, double b){return foo_(a,b);}
};


int main(int argc, char const *argv[]) {
    Test bar = Test(foo);
    bar.callFoo(2,3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sin*_*all 5

你几乎做得对,但忘记了构造函数中的类型setFoo:

#include <functional>
#include <iostream>

double foo(double a, double b) {
    return a + b;
}

class Test {
private:
    std::function<double(double, double)> foo_;
public:
    // note the argument type is std::function<>
    Test(const std::function<double(double, double)> & foo) : foo_(foo) {}
    // note the argument type is std::function<> 
    void setFoo(const std::function<double(double, double)>& foo) { foo_ = foo; }
    double callFoo(double a, double b) { return foo_(a, b); }
};

int main(int argc, char const *argv[]) {
    Test bar = Test(foo);
    bar.callFoo(2, 3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,使用typedef来避免冗长复杂的名称通常是有益的,例如,如果你这样做的话

typedef std::function<double(double,double)> myFunctionType
Run Code Online (Sandbox Code Playgroud)

你可以myFunctionType随处使用,这更容易阅读(假设你发明了一个比"myFunctionType"更好的名字)并且更加整洁.