无法从通用参考中捕获lambda中的参考

Cannot capture reference in lambda from universal reference?

本文关键字:参考 lambda      更新时间:2023-10-16

我试图弄清楚为什么无法通过参考传递捕获的变量将捕获变量传递给FOO函数,下面显示的程序不会与以下错误一起编译:

error: invalid initialization of reference of type 
'Object&' from expression of type 'const Object'

是否有某种方法可以将通用参考完美地转发到lambda中,以便通过参考捕获以供以后使用?T型也可能是R值或R值和L值的组合,因此不能总是通过参考捕获它们。

struct Object
{
};
void foo(Object& a)
{
}
template<typename... T>
auto bar(T&&... values)
{
    return [values...](){
        foo(values...);
    };
}
int main ()
{
    Object obj;
    auto lambda = bar(obj);
    return 0;
}

您是通过按值捕获值将值存储为const成员在闭合中的值,并且它们不能与非const lvalue参考结合。对于捕获by-ref,您忘了放置"&amp;"在值之前:

return [&values...](){
    foo(values...);
};

一个小例子。

两个文件之间的唯一差异:

diff omg.cpp nyan.cpp 
6c6
<   return [values...]{ foo(values...); };
---
>   return [&values...]{ foo(values...); };

用副捕获来编译一个:

$ g++ -std=c++14 omg.cpp && ./a.out 
omg.cpp: In instantiation of ‘bar(T&& ...)::<lambda()> [with T = {int&}]’:
omg.cpp:6:16:   required from ‘struct bar(T&& ...) [with T = {int&}]::<lambda()>’
omg.cpp:6:38:   required from ‘auto bar(T&& ...) [with T = {int&}]’
omg.cpp:11:16:   required from here
omg.cpp:6:25: error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers
  return [values...]{ foo(values...); };
                  ~~~^~~~~~~~~~~
omg.cpp:3:6: note:   initializing argument 1 of ‘void foo(int&)’
 void foo(int &a) { std::cout << a << std::endl; }
  ^~~

编译另一个:

$ g++ -std=c++14 nyan.cpp && ./a.out 
42
314