I want to use a library (nlopt) that has a function set_min_objective which takes a pointer to a numerical function myfunc and find its minimum. I would like to create a class that will contain a suitably initialized member function. set_min_objective would then find an optimum in a specific instance (myP in the example below). The call sequence is:
opt.set_min_objective(myfunc, NULL);
and I would like to use something like:
opt.set_min_objective(myP.f, NULL);
the error I get when compiling this is:
main.cpp: In function 'int main()':
main.cpp:79:34: error: no matching function for call to 'nlopt::opt::set_min_objective(<unresolved overloaded function type>, NULL)'
../lib/nlopt.hpp:335:10: note: candidates are: void nlopt::opt::set_min_objective(double (*)(unsigned int, const double*, double*, void*), void*)
../lib/nlopt.hpp:342:10: note: void nlopt::opt::set_min_objective(double (*)(const std::vector<double>&, std::vector<double>&, void*), void*)
../lib/nlopt.hpp:368:10: note: void nlopt::opt::set_min_objective(double (*)(unsigned int, const double*, double*, void*), void*, void* (*)(void*), void* (*)(void*))
What would be the simplest solution to have set_min_objective accepts myP.f as a normal pointer to function ? Note that myP.f and myfunc have the same arguments and return value types.
Thank you,
JD
You can't do that directly. You are trying to pass a pointer-to-member-function as a pointer-to-function. The way to go is to write a wrapper function (a normal function) which, for example, delegates the calculation to member function of your object, which is, for example, a global object.
EDIT
Actually, you are lucky: the second parameter to opt.set_min_objective
is a pointer to your data which will be passed to the function you pass pointer to as first parameter. This means that your wrapper function doesn't have to use a global object.
class YourClass
{
public:
double f(unsigned int i, const double*, double*, void*);
};
double wrapper(unsigned int i, const double* a, double* b, void* o) {
// not sure what you'd need the last param for, but you say you have it...
reinterpet_cast<YourClass*>(o)->f(i, a, b, o);
}
and then:
YourClass myP;
opt.set_min_objective(wrapper, &myP);
Another edit. Someone else had a similar problem before you: http://www.cplusplus.com/forum/general/73166/
来源:https://stackoverflow.com/questions/12377344/pointer-to-function-to-member-function