首页 > 解决方案 > 非本地 lambda 表达式不能有默认捕获

问题描述

在将字符串解码为操作时,我使用 lambda 表达式来减少 else-if 块,例如“sin”-> std::sin(x)。我在头文件中定义了一个结构:

struct func{
    std::string symbol;
    uint8_t type;

    std::function<double (double, double)> operate;
};

wheresymbol是表示函数的字符串,type是函数接受的输入数。在cpp文件中,我初始化一个func对象如下: func f1{"sin", ONE_INPUT, [=] (double a, double b){return std::sin(a);}};

但是,当我使用 编译 cpp 文件时g++ calc.cpp -o2 -std=c++17 -o calc.out,每个func对象的实例化都会出错: error: non-local lambda expression cannot have a capture-default

我试过在线搜索这个错误,但我发现的只是这个讨论帖子,解决方案说要确保我的 g++ 是 7.4 或更高版本。但是,我的 clang 版本是 12.0.0,所以我怀疑这是问题所在。

这是一个MRE:

#define ONE_INPUT 0
#define TWO_INPUT 1

#include <iostream>
#include <cmath>
#include <math.h>
#include <string>
#include <cstdint>
#include <functional>

struct func{
    std::string symbol;
    uint8_t type;

    std::function<double (double, double)> operate;
};

int main(int argc, char** argv){
    func f1{"sin", ONE_INPUT, [=] (double a, double b){return std::sin(a);}};
    func f2{"cos", ONE_INPUT, [=] (double a, double b){return std::cos(a);}};
    func f3{"tan", ONE_INPUT, [=] (double a, double b){return std::tan(a);}};
}

标签: c++lambda

解决方案


推荐阅读