使用函子将函数传递给另一个函数
C++ Passing a function to a function using 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;
};
我想把这些函数中的一个传递给另一个函数:
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;
}
我确保这是一个完整的工作演示,所以你可以复制它来测试它。您将看到两个不同的数字打印到终端,从而证明多态性可以与函子一起使用。再次强调,我并不是说这比模板答案更好,我只是想指出这不是唯一的答案。虽然这个问题已经得到了解答,但我希望这能帮助到任何想要了解的人。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?