无法从通用参考中捕获lambda中的参考
Cannot capture reference in lambda from universal reference?
我试图弄清楚为什么无法通过参考传递捕获的变量将捕获变量传递给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
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 可组合的lambda/std::函数与std::可选
- C++错误消息*成员参考.**初学者*
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 参考资源文件VC++中的$(SolutionDir)
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- 如何将lambda作为模板类的成员函数参数
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 在 lambda 捕获中声明的变量的类型推导
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 为什么lambda在clang上崩溃而不是在gcc上崩溃
- 模板函数指针和lambda
- Lambda闭包左值可以作为右值参考参数传递
- Lambda通过参考传递的功能
- 无法从通用参考中捕获lambda中的参考
- 通过C 11 lambda中的参考捕获参考
- std :: async和std ::包装rvalue参考lambda时的差异
- 更新 Lambda 的参考数据