c++ - 如何在此 C++ lambda 表达式中获取局部变量?
问题描述
在以下代码中:
#include "Simple_window.h"
#include "Graph.h"
int fac(int n) // factorial(n); n!
{
int r = 1;
while(n>1) {
r *= n;
--n;
}
return r;
}
double term(double x,int n) { return pow(x,n)/fac(n); }
double expe(double x,int n) // sum of n terms for x
{
double sum = 0;
for(int i = 0; i<n; ++i) sum += term(x,i);
return sum;
}
int main() {
Simple_window win {Point{100,100},xmax,ymax,""};
for(int n = 0; n<50; ++n) {
ostringstream ss;
ss << "exp approximation; n==" << n;
win.set_label(ss.str());
// get next approximation:
Function e {[n](double x) { return expe(x,n); },
-10,10,Point{300,300},200,30,30; // ***this line doesn't compile***
win.attach(e);
win.wait_for_button();
win.detach(e);
}
}
从 Stroustrup 的“使用 C++ 的原理和实践”一书中,n
当我尝试编译局部变量时,它没有被采用,并给出错误消息:
构造函数 Graph_lib::Function::Function 没有实例与参数列表一致
问题是什么?
顺便说一句,用于书籍的支持代码是https://web.archive.org/web/20191217104940/http://www.stroustrup.com/Programming/PPP2code
解决方案
您的帖子不接近最小可重现示例
这是最小可重现示例的示例。
在 Graph.hFunction
中,变量为Fct
. Fct
在哪里typedef double Fct(double);
。
根据这篇文章,lambda 表达式不会自动转换为函数,除非它不通过捕获任何内容来创建闭包对象。
检查这个例子
typedef double Fct ( double );
typedef double bct ( double, int );
struct Foo{
Foo( Fct f ){};
};
struct bar{
bar( bct f){};
};
int main(){
int n(1);
Foo f{ [](double x){ return x; } };
//Foo f{ [n](double x){ return x*n; } }; // <=== this won't compile
bar b{[](double x, int n){return x*n;}};
}
要在没有闭包的情况下传递n
into 函数,您可以f
将签名从
typedef double Fct ( double );
typedef double Fct ( double, int ); 就像我的例子bar
写一个带常数的函数
n
。(强烈不建议,除非您从不维护代码)全局变量,使其可以
n
在函数外部进行更改。
推荐阅读
- python - Selenium,如何使用 chrome 和 python 重新加载禁用的图像?
- docker - 从 VMWare Workstation VM 访问在主机上运行的 Docker
- php - html下拉菜单在wordpress网站中不起作用
- algorithm - 找到一个最接近 0 且未被任何区间采用的数字(表示左右值的两个数字的集合)
- api - NoSuchMethodError:在 null 上调用了 getter 'length'。在调用 put api 时?
- google-sheets - 使用 Arrayformula 在 A 列中显示百分比符号
- r - 为什么 Trelliscope 查看器显示空面板,没有图像?
- javascript - 多标签对齐
- .net - 为什么我在 VSTO 插件中的图标看起来很模糊?
- android - 莫西。父抽象类中的@Json 注解被忽略