Is there a way in C ++ to effectively create a closure that will be a function pointer? I am using the Gnu Science Library and I need to create a gsl_function . This function should effectively "close" a couple of parameters available when creating it. Is there a good trick to create closures, so I donβt need to pass all of them as parameters in the gsl_function structure? If not, should I just pass a pointer to an array containing these parameters?
EDIT I tried using boost :: bind as follows:
#include <gsl/gsl_integration.h> #include <boost/bind.hpp> #include "bondpricecalculator.h" #include "functions.h" double integrand (double xi, double t, double x, void * p) { Functions *functions = (Functions *) p; double vx = functions->v(x); return functions->rho0(x)*exp(vx * xi - 0.5 * vx * vx * t); } double BondPriceCalculator::value(double t, double T, double xi) { gsl_integration_workspace * w = gsl_integration_workspace_alloc (10000); gsl_function F; F.function = &boost::bind(integrand, xi, t, _1, _2); F.params = &functions; double integral_t; double integral_T; double error; int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_T, &error); if(res) { throw "Error intgrating"; } int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_t, &error); if(res) { throw "Error intgrating"; } return integral_T/integral_t; }
but I got the following error message:
/home/ga/svn/PhD/inflation/cpp/ioi/bondpricecalculator.cpp:20: error: cannot convert 'boost::_bi::bind_t<double, double (*)(double, double, double, void*), boost::_bi::list4<boost::_bi::value<double>, boost::_bi::value<double>, boost::arg<1>, boost::arg<2> > >*' to 'double (*)(double, void*)' in assignment