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

Passing function to class in C++

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

我想将一个函数存储在一个类中,并在成员函数中简单地调用这个函数。我知道使用函数指针可以做到这一点,但我想为此使用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;
}

你几乎做对了,但忘记了构造函数中的类型,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;
}

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

typedef std::function<double(double,double)> myFunctionType

你可以在任何地方使用myFunctionType,这更容易阅读(前提是你发明了一个比"myFunctionType"更好的名字)并且更整洁。