I want to pass a member function of my C++ class to another member function of the same class. I did some research and found these similar questions on SO.
Passing a member function as an argument in C++
Function pointer to member function
They don't cover my specific case in an identical manner, but I wrote my code and would think that I adjusted the right parts to make it work in my situation. However, the compiler seems to disagree with me on that...
I have the following setup in my C++ class:
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;
}
However, passing the thresholdFunction
as an argument like this doesn't work. The compiler complains with the following error:
error : called object type
'double (CutDetector::*)(vector<double>)'
is not a function or function pointer
Can anyone see why my setup doesn't work and suggest how I can make it so that it works? Basically what I want is to be able to pass any member function that calculates a threshold (ie calcMean
, calcMeanMinMax
, calcMedian
) to the other member function thresholdForFrameIndex
.
To invoke a pointer to member function, you need to supply an object:
double threshold = (this->*thresholdFunction)(window);
^^^^^^^^ ^
You can't call a member function without an instance of the class. You need to do something like this:
CutDetector cd;
double threshold = (cd.*thresholdFunction)(window);
Or if you have a CutDetector
pointer somewhere:
double threshold = (pcd->*thresholdFunction)(window);
Or if thresholdForFrameIndex
is a member function:
double threshold = (this->*thresholdFunction)(window);
I think it would be easier for you here to make calcMean
, calcMeanMinMax
and calcMedian
static functions and treat like all others non-member functions. Others answers are correct, but in your case i guess that would be better for class design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.