Function pointer to non-static class member

closed account (9267ko23)
Hi,

I have the following problem: I am using NLOpt for optimization. The API provides functions to set the objective. This is done as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
double objective(const vector<double> &x, vector<double> &grad, void *data) {
  return x[1]*x[0];
}

int main(){
  nlopt::opt opti(nlopt::LD_MMA,2);
  opti.set_min_objective(objective,NULL);
  vector<double> x(2);
  x[0] = 0.0; x[1] = 1.0;
  double min;
  double res = opti.optimize(x,min);
  return res;
}


Now I want to make the function objective a member of a class:
1
2
3
4
class Foo {
public:
  double objective(...){..}
};


How can I give this method to opti.optimize? If I make objective static I can use
 
opti.optimize(Foo::objective,NULL);

but I do not want to have a static member. Is it possible to create an object of type Foo and give it to opti.optimize?
Use the `data' parameter to pass the object
1
2
3
4
5
6
7
8
9
class Foo{
public:
   double objective(const vector<double> &x, vector<double> &grad);
};

double wrapper(const vector<double> &x, vector<double> &grad, void *data){
   Foo &obj = reinterpreter_cast<Foo*>(data);
   return obj.objective(x,grad);
}



Don't know how to call it, as you have no provided documentation and your example is not consistent.
Topic archived. No new replies allowed.