DrDirk
DrDirk

Reputation: 1997

C++: Cast std::function to gsl_function

I want to use the GNU Scientific Library and need to cast std::function to the gsl_function, which is of type double (* function) (double x, void * params).

Until now I simply tried:

class Numerics {
 public:
  ....
  double integrate(function<double(double)> &func) {
    double result, error;
    gsl_function F;
    F.function = static_cast<(*)(double, void *)>( func );
    gsl_integration_qag(&F, 0, 1, epsabs_, epsrel_, 1000, 6, w_, &result, &error);
    return result;
  }
  ...
};

, which hands me back the error

type name requires a specifier or qualifier

Upvotes: 3

Views: 694

Answers (1)

std::function is a type erasing "general functor" holder from the standard library. It's not implicitly convertible to regular function pointers, nor should you attempt to do it, since you'd just end up shooting yourself in the foot. You need to wrap the call to func with a proper regular function that conforms to the gsl_function::function typedef.

gsl_function::function accepts a void* as extra function parameter. That's your hook for passing an object like std::function into it, to facilitate the call. You can use a capture-less lambda (which will convert implicitly to a free function pointer) in order to keep things local:

gsl_function F = {
  [](double d, void* vf) -> double {
    auto& f = *static_cast<std::function<double(double)>*>(vf);
    return f(d);
  },
  &func
};

Upvotes: 6

Related Questions