使用函子将函数传递给另一个函数

C++ Passing a function to a function using functors

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

有两个函子:

class SFunctor {
public:
    SFunctor(double a) { _a = a; }
    double operator() (double t) { return _a * sin(t); }
private:
    double _a;
};
class CFunctor {
public:
    CFunctor(double b) { _b = b; }
    double operator() (double t) { return _b * cos(t); }
private:
    double _b;
};

我想把这些函数中的一个传递给另一个函数:

double squarer(double x, ??______?? func) {
      double y = func(x);
      return y * y;
}

在我的主程序中,我想这样调用:

CFunctor sine(2.);
SFunctor cosine(4.);
double x= 0.5;
double s = squarer(x, sine);
double c = squarer(x, cosine); 

我如何指定函数基金,那就是在它前面的地方??_??div ?

您可以简单地使用模板

template <class F>
double squarer(double x, F& func) {
      double y = func(x);
      return y * y;
}

我不是在敲上面的模板答案。事实上,它可能是两者中更好的选择,但我想指出的是,多态性也可以做到这一点。例如…

#include <math.h>
#include <iostream>
using std::cout;
using std::endl;
class BaseFunctor {
 public:
   virtual double operator() (double t) = 0;
 protected:
   BaseFunc() {}
};
class SFunctor : public BaseFunctor {
 public:
   SFunctor(double a) { _a = a; }
   double operator() (double t) { return _a * sin(t); }
 private:
   double _a;
};
class CFunctor : public BaseFunctor {
 public:
   CFunctor(double b) { _b = b; }
   double operator() (double t) { return _b * cos(t); }
 private:
   double _b;
};
double squarer(double x, BaseFunctor& func) {
   double y = func(x);
   return y * y;
}
int main() {
   SFunctor sine(.2);
   CFunctor cosine(.4);
   double x = .5;
   cout << squarer(x,sine) << endl;
   cout << squarer(x,cosine) << endl;
}

我确保这是一个完整的工作演示,所以你可以复制它来测试它。您将看到两个不同的数字打印到终端,从而证明多态性可以与函子一起使用。再次强调,我并不是说这比模板答案更好,我只是想指出这不是唯一的答案。虽然这个问题已经得到了解答,但我希望这能帮助到任何想要了解的人。