我正在使用 gsl 集成一个功能。该函数构建在一个 lambda 函数中,该函数的输入为 double 和 void *,输出为 double 。 现在,如果我在没有任何变量捕获的情况下使用 lambda,一切正常。但是,如果我进行变量捕获,它就不再起作用了。
谁能解释一下为什么会这样?
这是我编写的两段代码来解释我的问题:
这个很好用:
int main(int argc, char **argv)
{
double beg = 0;
double end = 10;
auto f = [] (double x, void * p) {return 2.0;};
gsl_integration_workspace * w = gsl_integration_workspace_alloc (GSL_INTEGRATION_WORKSPACE_SIZE);
double result;
double error;
gsl_function F;
F.function = f;
F.params = NULL;
gsl_integration_qags (&F, beg, end, 0, GSL_INTEGRATION_RELATIVE_PRECISION, GSL_INTEGRATION_WORKSPACE_SIZE, w, &result, &error);
cout<<result<<endl;
}
虽然这个
int main(int argc, char **argv)
{
double beg = 0;
double end = 10;
double p = 2.0;
auto f = [&] (double x, void * p) {return p;};
gsl_integration_workspace * w = gsl_integration_workspace_alloc (GSL_INTEGRATION_WORKSPACE_SIZE);
double result;
double error;
gsl_function F;
F.function = f;
F.params = NULL;
gsl_integration_qags (&F, beg, end, 0, GSL_INTEGRATION_RELATIVE_PRECISION, GSL_INTEGRATION_WORKSPACE_SIZE, w, &result, &error);
cout<<result<<endl;
}
产量就行
F.function = f;
以下错误:
Assigning to 'double (*)(double, void *)' from incompatible type '<lambda at /[omissis]/main.cpp>'
最佳答案
@user657267 给出的答案是正确的。这就是为什么需要一个小的包装器来将带捕获的 lambas 转换为 gsl_function。
Here is the wrapper for the f gsl_function和 Here is the wrapper for the fdf gsl_function
在使用这两个答案中提出的包装器后,您可以通过以下方式将 lambda 函数转换为 gsl_function(我还没有发明带有 std::function 的版本,这是一个众所周知的答案。我没有的模板版本'在我回答之前没见过)。
// std::function version
double a = 1;
gsl_function_pp Fp([=](double x)->double{return a*x;});
gsl_function *F = static_cast<gsl_function*>(&Fp);
//template version
double a = 1;
auto ptr = [=](double x)->double{return a*x;};
gsl_function_pp<decltype(ptr)> Fp(ptr);
gsl_function *F = static_cast<gsl_function*>(&Fp);
关于c++ - lambda函数与gsl的数值积分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626158/