【发布时间】:2016-03-23 17:54:00
【问题描述】:
在 C++ 中,我们可以像这样将函数/函子传递给函数:
template <typename F>
void doOperation(int a, int b, F f){
std::cout << "Result: " << f(a,b) << std::endl;
}
然后我们可以同时使用函数和仿函数:
int add(const int &a, const int &b){ return a+b; }
struct subtract(){
void operator() (const int &a, const int &b) { return a-b; }
};
并以下列方式使用它:
doOperation(1,2,add);
doOperation(5,2,subtract());
我的问题是,我可以对一个类做类似的事情并将一个函数作为参数传递给一个类,存储它并稍后使用它?例如
template <typename F>
class doOperation{
public:
doOperation(int &a, int &b, F f) : a(a), b(b), f(f) {};
void setOperands(int &a, int &b) { this->a = a; this->b = b };
void performCalculation(){
std::cout << "Result: " << f(a,b) << std::endl;
}
private:
int a,b;
F f;
}
这样我们就可以给它分配一个函数,然后再使用它:
doOperation summing(1,2,add);
summing.setOperands(2,3);
summing.performCalculation();
doOperation subtraction(7,3,subtract());
subtraction.performCalculation();
如果我的例子是有效的,我会很感激这里对机制的解释,因为我似乎有点迷失了。万一我错过了什么,我正在寻找有关这是否可以实现的提示。
最后,我将如何在其他函数和类中使用这样的class doOperation。例如,在成员函数中定义这样的东西需要我模板化新类、它的成员函数,以及如何声明和使用它:
class higherFunctionality{
public:
higherFunctionality() {...}
void coolThings(){
doOperation *myOperation = operationFactory( ... );
myOperation->setOperands(4,5);
myOperation->performCalculation();
}
};
【问题讨论】:
-
搜索:函数指针。
-
你考虑过
std::function吗?