如何解决如何在此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
解决方法
您的帖子与Minimal Reproducible Example距离很近
以下是“最小可复制示例”的示例。
在Graph.h中,Function
的变量为Fct
。
Fct
是typedef double Fct(double);
的地方。
但是,lambda不会自动转换为函数,除非它不会通过捕获任何内容来创建闭包对象。
选中此example
typedef double Fct ( double );
struct Foo{
Foo( Fct f );
};
int main(){
int n(1);
Foo f{ [](double x){ return x; } };
//Foo f{ [n](double x){ return x*n; } }; // <=== this won't compile
}
相关帖子:https://stackoverflow.com/a/45565056/4123703
要将n
传递到功能f
中,您可以
-
将签名从
typedef double Fct ( double );
更改为typedef double Fct(double,int); -
用常数
n
编写一个函数。 -
(强烈建议不要使用,除非您从不维护代码)全局变量,以便可以在函数外部更改
n
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。