在 C++ 中的 lambda 表达式中非法捕获
Illegal capture in lambda expression in c++
>我很难为一个相当简单的lambda表达式编写有效的捕获。这是我尝试编译的代码:
#include <iostream>
#include <vector>
class State { public:
int i;
float f;
State(int i,float f){this->i = i; this->f = f;}
};
typedef State (*FunctionType)(const State &state);
int main(int argc, char **argv)
{
std::vector<FunctionType> funcs;
funcs.push_back(
[](const State &state)
{
return State(state.i+7,state.f-3.5);
});
State s(100,5.5);
int m = 5;
funcs.push_back(
[](const State &state)
// [=](const State &state)
// [&](const State &state)
{
return State(m,m+0.5);
});
for (auto func : funcs)
{
std::cout << func(s).i << " " << func(s).f << "n";
}
return 0;
}
当我编译它时
$ g++ -std=c++17 main.cpp -o main
我收到以下错误(以及更多错误(,表明我无法捕获m
:
main.cpp: In lambda function:
main.cpp:32:17: error: ‘m’ is not captured
return State(m,m+0.5);
^
main.cpp:28:4: note: the lambda has no capture-default
[](const State &state)
^
main.cpp:25:6: note: ‘int m’ declared here
int m = 5;
^
您确实需要一个注释版本来捕获m
[=](const State &state) { return State(m, m + 0.5); }
[&](const State &state) { return State(m, m + 0.5); }
或显式捕获:
[m](const State &state) { return State(m, m + 0.5); }
[&m](const State &state) { return State(m, m + 0.5); }
但是你会遇到问题:
std::vector<FunctionType> funcs;
funcs.push_back([=](const State &state) { return State(m, m + 0.5); })
捕获 lambda 不能衰减到函数指针,您需要更改
typedef State (*FunctionType)(const State &state);
到
using FunctionType = std::function<State(const State&)>;
可以处理λ
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- "class":非法使用此类型作为表达式 如何解决?
- 在 C++ 中的 lambda 表达式中非法捕获
- 调用模板类成员时非法使用此类型作为表达式
- C2276 '&':对绑定成员函数表达式的非法操作
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 错误 C2275 RHandle:非法使用此类型作为表达式
- '&' :对绑定成员函数表达式的非法操作
- 错误:非法使用此类型作为表达式.C++
- LAMBDA 错误:类型 'void' 的条件表达式是非法的
- 为什么double v2=((double)51/4)%2是非法表达式ni c++
- "&":对绑定成员函数表达式的非法操作。从关键点矢量 OpenCV 获取容量
- 非法使用type作为表达式
- 无法在VS 14 CTP中使用auto声明lambda:类型为'void'的条件表达式是非法的
- std::string:将此类型非法用作表达式
- "!"绑定成员函数表达式的非法操作
- 奇怪的错误 C2275 ..非法使用此类型作为成员函数模板和 lambda 的表达式
- 非法使用此类型作为表达式(错误)c++
- 非法使用此类型作为表达式- VS 2012