C++ 中有没有办法有效地创建一个闭包,它将是一个函数指针?我正在使用 Gnu 科学图书馆,我必须创建一个 gsl_function 。这个函数需要在我创建它时有效地“关闭”几个可用的参数。有没有一个很好的技巧来创建一个闭包,这样我就不必在 gsl_function 结构中将它们全部作为参数传递?如果没有,我应该只传递一个指向包含这些参数的数组的指针吗?

编辑
我曾尝试像这样使用 boost::bind:

#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;
}

但我收到以下错误消息:
/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

最佳答案

我在下面找到了代码。

http://bytes.com/topic/c/answers/657124-interface-problem

// Use in combination with boost::bind.
template<class F>
static double gslFunctionAdapter( double x, void* p)
{
    // Here I do recover the "right" pointer, safer to use static_cast
    // than reinterpret_cast.
        F* function = static_cast<F*>( p );
    return (*function)( x );
}

template<class F>
gsl_function convertToGslFunction( const F& f )
{
    gsl_function gslFunction;

    const void* p = &f;
    assert (p != 0);

    gslFunction.function = &gslFunctionAdapter<F>;
    // Just to eliminate the const.
    gslFunction.params = const_cast<void*>( p );

        return gslFunction;
}

并使用这个
gslFunction gslF = convertToGslFunction( boost::bind( &Sde::drift, &sde, _1 ) );

关于c++ - 在 C++ 中用作闭包的函数指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3194119/

10-15 06:58