Reputation: 55
I am working on an optimization algorithm, in my algorithm, I need to use a function pointer to pass the function into the optimizer
the class definition:
class Downhill
{
public: //
Downhill(std::string fpath);
~Downhill();
void run();
private:
/*objfun will be passed to amoeba function by function pointer*/
float objfun1(float *p,int ndim);
float objfun2(float *p,int ndim);
float objfun3(float *p,int ndim);
void amoeba(float **p, float pval[], int ndim, float(*funk)(float *, int ndim), float ftol, int &niter);
private:
float ftol;
float TINY = 1E-10;
int NMAX = 5000;
std::ofstream fout;
};
In the declaration of member function run(), I did as:
float(*funk)(float *p, int dim);
funk = &(this->objfun1); // I define the function pointer here
amoeba(p, pval, ndim, funk, ftol, niter);
And I had the compiler errer:
error C2276: '&': illegal operation on bound member function expression
How can I refer a member function in another member function? Thank you very much!
Upvotes: 0
Views: 90
Reputation: 4764
When taking the address of a method pointer, you need to include the name of the class. So in this case, the appropriate syntax would be:
&Downhill::objfun1
At the same time, a non-static method pointer is not interchangeable with a regular function pointer. So you would need to declare the third argument of amoeba
as:
float(Downhill::*funk)(float *, int ndim)
And then you would need to call the function as this->*funk(...)
. If you need to bundle the identity of the object with a pointer, then you might consider making the third argument a std::function<float(float*, int)>
(and then using a lambda or std::bind
). However in your case that might not be necessary.
Upvotes: 5