c++ - 非本地 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);}};
}
解决方案
推荐阅读
- python - 字典仅捕获最后一个键值对 Python
- ios - 无效的 iOS 捆绑包
- python - 如何转换需要用户输入才能在不和谐机器人中工作的 Python 代码?
- performance - TFJS 中 Eager 样式的性能成本是多少?
- javascript - 如何使用 Jest 和 Enzyme 在 componentDidMount 中验证 console.log 是否被调用?
- amazon-rds - 本地运行SAM时如何连接RDS实例?
- python - 数据框排序和选择不起作用
- json - 如何在 Logic App 中将字符串解析为 JSON?
- sql - 使用 Group by 的 Oracle SQL 查询不起作用
- c# - 如何使用 EF Core fluent api 创建多个索引?