首页 > 解决方案 > 如何在此 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

标签: c++

解决方案


您的帖子不接近最小可重现示例

这是最小可重现示例的示例。

在 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;}};

}

要在没有闭包的情况下传递ninto 函数,您可以f

  1. 将签名从typedef double Fct ( double );typedef double Fct ( double, int ); 就像我的例子bar

  2. 写一个带常数的函数n

  3. (强烈不建议,除非您从不维护代码)全局变量,使其可以n在函数外部进行更改。


推荐阅读