我正在与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/