c++ - 如何在此C++ lambda表达式中采用局部变量?

标签 c++

在下面的代码中:

#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时未使用它,并给出了错误消息:

No instance of the constructor Graph_lib::Function::Function coincides with the argument list


问题是什么?
顺便说一句,用于书籍的支持代码是https://web.archive.org/web/20191217104940/http://www.stroustrup.com/Programming/PPP2code

最佳答案

您的帖子距离Minimal Reproducible Example不近
这是“最小可复制示例”的示例。
在Graph.h中,Function带有Fct变量。
其中Fcttypedef 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
  • 关于c++ - 如何在此C++ lambda表达式中采用局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63351768/

    相关文章:

    c++ - 使用辅助存储检查基于磁盘的合并排序的性能

    c++ - 如何获取数组的大小?

    c++ - 在OpenGL中用鼠标拾取在3D空间中拖动3D点的最佳方法?

    c++ - 在派生类中重写运算符 new/delete

    c++ - 为什么 injected-class-name 有时不被视为类模板中的模板名称?

    c++ - 作为通用指针类型传递的智能指针在传递给另一个函数之前是否需要释放?

    c++ - 链中的最后一个任务应该返回什么 - C++ Rest sdk?

    c++ - 重复键的 bimap 使用

    c++ - 编译错误: could not convert

    c++ - 如何在C++中添加多个字符串