C function pointers with C++11 lambdas

后端 未结 5 1144
自闭症患者
自闭症患者 2020-11-30 10:55

So i\'m trying to write an Integration function to be used with c++11 lambdas. The code looks something like this:

double Integrate(std::function

        
5条回答
  •  失恋的感觉
    2020-11-30 11:29

    Looks like the gsl library requires a function pointer. A lambda which does not capture can be converted to a function pointer. Any lambda can be converted to a std::function. But a std::function cannot be converted to a function pointer.

    You could try:

    struct functor_and_params {
      std::function f;
      void* params;
      static double invoke(double x, void* ptr) {
          functor_and_params& f_and_p = *reinterpret_cast(ptr);
          return f_and_p.f(x, f_and_p.params);
      }
    };
    
    double Integrate(std::function func,
                     double a,double b,std::vector & params) {
        functor_and_params f_and_p{ func, ¶ms };
        gsl_function F;
        F.function = &functor_and_params::invoke;
        F.params = &f_and_p;
        //...
     }
    

提交回复
热议问题