在 C++ 中的 lambda 表达式中非法捕获

Illegal capture in lambda expression in c++

本文关键字:非法 表达式 C++ 中的 lambda      更新时间:2023-10-16

>我很难为一个相当简单的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&)>;

可以处理λ