【发布时间】:2015-07-17 18:19:09
【问题描述】:
我想将我的 C++ 类的成员函数传递给同一类的另一个成员函数。我做了一些研究,在 SO 上发现了这些类似的问题。
Passing a member function as an argument in C++
Function pointer to member function
他们没有以相同的方式涵盖我的具体案例,但我编写了我的代码并认为我调整了正确的部分以使其适用于我的情况。但是,编译器似乎不同意我的观点......
我的 C++ 类中有以下设置:
CutDetector.h
class CutDetector {
double thresholdForFrameIndex(int frameIndex, vector<double> diffs, int steps, double (CutDetector::*thresholdFunction)(vector<double>diffs)); // should take other functions as args
double calcMean(vector<double> diffs); // should be passed as argument
double calcMeanMinMax(vector<double> diffs); // should be passed as argument
double calcMedian(vector<double> diffs); // should be passed as argument
}
CutDetector.h
double thresholdForFrameIndex(int frameIndex, vector<double> diffs, int steps, double (CutDetector::*thresholdFunction)(vector<double>diffs)) {
vector<double> window = ... init the window vector ;
double threshold = thresholdFunction(window);
return threshold;
}
但是,将thresholdFunction 作为这样的参数传递是行不通的。编译器报错如下:
错误:调用对象类型
'double (CutDetector::*)(vector<double>)'不是函数或函数指针
谁能看到我的设置为什么不起作用并建议我如何使它起作用?基本上我想要的是能够将任何计算阈值的成员函数(即calcMean、calcMeanMinMax、calcMedian)传递给另一个成员函数thresholdForFrameIndex。
【问题讨论】:
-
1.那些 both 真的在 CutDetector.h 中吗,以及 2. 您是否有意省略了第二个 sn-p 定义中的
CutDetector::限定符(即,这是一个免费功能,而 不是 在前一个类中声明的成员)? -
您可能希望将 vector
作为 const & 传递以避免代价高昂的复制操作。
标签: c++ functional-programming function-pointers member-function-pointers