Zeb*_*ish 1 c++ lambda capture
我想知道是否可以捕获函数结果:
int main()
{
struct A { int a; int func() { return a; } };
A a;
auto lambda = []() {};
// I WANT THE LAMBDA TO HAVE A COPY OF a.func();
// In other words I want capture the return value of a.func()
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?我知道在较新的 C++ 标准中,您可以在捕获列表中创建新变量,所以像这样吗?
auto lambda = [int copy = a.func()] () { cout << copy; }
Run Code Online (Sandbox Code Playgroud)
语法略有不同。捕获组中实体的类型是从初始化器推导出来的,不能明确指定类型:
auto lambda = [copy = a.func()] () { std::cout << copy; };
// ^ no int
Run Code Online (Sandbox Code Playgroud)
您也可以在捕获组中创建多个不同类型的实体,如果您只是通过,以下方式将它们分开:
auto lambda = [x = a.func(), y = a.func2()] () { std::cout << x << y; };
Run Code Online (Sandbox Code Playgroud)
这是一个演示。