我很难为一个简单的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;
^
答案 0 :(得分:3)
您确实需要一个注释版本来捕获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&)>;
可以处理lambda的