在C ++中如何正确传递成员函数作为参数?

时间:2015-05-07 09:10:17

标签: c++ functional-programming function-pointers member-function-pointers

我想将我的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>)'   不是函数或函数指针

任何人都可以看到为什么我的设置无法正常工作并建议我如何才能使其有效?基本上我想要的是能够将任何计算阈值的成员函数(即calcMeancalcMeanMinMaxcalcMedian)传递给另一个成员函数{ {1}}。

3 个答案:

答案 0 :(得分:2)

要调用指向成员函数的指针,您需要提供一个对象:

double threshold = (this->*thresholdFunction)(window);
                   ^^^^^^^^                 ^

答案 1 :(得分:2)

如果没有该类的实例,则无法调用成员函数。你需要做这样的事情:

CutDetector cd;
double threshold = (cd.*thresholdFunction)(window);

或者如果某处有CutDetector指针:

double threshold = (pcd->*thresholdFunction)(window);

或者如果thresholdForFrameIndex是成员函数:

double threshold = (this->*thresholdFunction)(window);

答案 2 :(得分:2)

我认为您可以更轻松地制作calcMeancalcMeanMinMaxcalcMedian 静态功能,并像对待所有其他非会员功能一样对待。其他答案是正确的,但在你的情况下,我认为这对于课堂设计会更好。