简体   繁体   English

C ++使用仿函数将函数传递给函数

[英]C++ Passing a function to a function using functors

I have two functors: 我有两个仿函数:

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;
};

I want to pass one or the other of these functions to another function: 我想将这些函数中的一个或另一个传递给另一个函数:

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

In my main program I want to make a call like this: 在我的主程序中,我想打个电话:

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

How do I specify the function fund, that is what goes in front of it in place of ?? 我如何指定功能基金,即前面的功能基金代替? _ ?? _ ?? ?

You can simply do it with templates 您只需使用模板即可

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

I'm not knocking on the above template answer. 我没有敲开上面的模板答案。 In fact, it may be the better choice of the two, but I wanted to point out that this can be done with polymorphism as well. 事实上,它可能是两者中更好的选择,但我想指出这也可以通过多态来完成。 For example... 例如...

#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;
}

I ensured that this was a full working demo, so you can just copy it to test it. 我确保这是一个完整的工作演示,所以你可以复制它来测试它。 You will indeed observe two different numbers print to the terminal, thus proving that polymorphism can be used with functors. 您将确实观察到两个不同的数字打印到终端,从而证明多态可以与仿函数一起使用。 Again, I'm not saying this is better than the template answer, I just wanted to point out that it isn't the only answer. 同样,我并不是说这比模板答案更好,我只想指出它不是唯一的答案。 Even though the question has been answered, I hope this helps inform anyone who wants to be informed. 即使这个问题已得到解答,我希望这有助于通知任何想要获得通知的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM