[英]Function passed as a class argument
在 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();
}
};
是的,但是您必須在實例化模板類時提供類型。 通常的處理方法是創建一個輔助函數:
template < typename Fun > struct operation_class
{
operation_class(Fun f) : fun{f} {}
Fun fun;
};
template < typename Fun >
operation_class<Fun> operation(Fun fun) { return operation_class<Fun>{fun}; }
int main()
{
auto op0 = operation(some_fun);
auto op1 = operation(some_functor{});
}
坦率地說,你最好只使用 lambda:
auto op0 = [a,b]() { return sum(a,b); };
auto op1 = [a,b]() { return subtract{a,b}(); }
// C++17:
auto op2 = [op=subtract{a,b}] { return op(); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.