Eloi Marks
Eloi Marks

Reputation: 7

C++ How to make a function overload that accepts class functions as argument

I'm using ALGLIB to run a LBFGS minimization of a given function. To do so I need to use the following statement:

alglib::minlbfgsoptimize(state, FunctionToOptimizeHere)

Here is one declaration of alglib::minlbfgsoptimize provided in the ALGLIB package:

void minlbfgsoptimize(minlbfgsstate &state,
void (*grad)(const real_1d_array &x, double &func, real_1d_array &grad, void *ptr),
void  (*rep)(const real_1d_array &x, double func, void *ptr) = NULL,
void *ptr = NULL,
const xparams _xparams = alglib::xdefault);

So when I create my function outside of any class as

void function(const alglib::real_1d_array& x, double& func, alglib::real_1d_array& grad, void* ptr)

It works fine but the problem is that I need to use it on a function that is inside a class it doesn't work. The arguments do not match because my function is now a:

void MyClass::Myfunction(const alglib::real_1d_array& x, double& func, alglib::real_1d_array& grad, void* ptr)

I can't figure it out how to overload minlbfgsoptimize to accept my (inside of a class) function. Can anybody help me with that? Thank you

Upvotes: 0

Views: 114

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Luckily, your library provides a way to pass context to the callback. You need an intermediate non-member or static member function (sometimes known as a "trampoline"). Something along these lines:

class MyClass {
  void DoActualWork(const alglib::real_1d_array& x, ...);
  static void Trampoline(const alglib::real_1d_array& x, ..., void* ptr) {
    static_cast<MyClass*>(ptr)->DoActualWork(x, ...);
  }
};

You would then call it this way:

MyClass myObject;
alglib::minlbfgsoptimize(state, MyClass::Trampoline, nullptr, &myObject);

Note how a MyClass pointer is passed to minlbfgsoptimize, in void* ptr parameter. The library then forwards it along to the callback, which recovers the original MyClass pointer and calls a member function through it.

Upvotes: 1

Related Questions