Capturing perfectly-forwarded variable in lambda(在 lambda 中捕获完美转发的变量)
问题描述
template<typename T> void doSomething(T&& mStuff)
{
auto lambda([&mStuff]{ doStuff(std::forward<T>(mStuff)); });
lambda();
}
使用 &mStuff 语法捕获完美转发的 mStuff 变量是否正确?
Is it correct to capture the perfectly-forwarded mStuff variable with the &mStuff syntax?
或者对于完美转发的变量是否有特定的捕获语法?
Or is there a specific capture syntax for perfectly-forwarded variables?
如果完美转发的变量是参数包怎么办?
推荐答案
捕获完美转发的 mStuff 变量是否正确&mStuff 语法?
Is it correct to capture the perfectly-forwarded mStuff variable with the &mStuff syntax?
是的,假设您不在 doSomething 之外使用此 lambda.您的代码捕获每个引用的 mStuff 并将其正确转发到 lambda 中.
Yes, assuming that you don't use this lambda outside doSomething. Your code captures mStuff per reference and will correctly forward it inside the lambda.
对于作为参数包的 mStuff,使用带有包扩展的简单捕获就足够了:
For mStuff being a parameter pack it suffices to use a simple-capture with a pack-expansion:
template <typename... T> void doSomething(T&&... mStuff)
{
auto lambda = [&mStuff...]{ doStuff(std::forward<T>(mStuff)...); };
}
lambda 捕获每个引用的 mStuff 的每个元素.闭包对象为每个参数保存一个左值引用,无论其值类别如何.完美转发仍然有效;事实上,甚至没有区别,因为命名的右值引用无论如何都是左值.
The lambda captures every element of mStuff per reference. The closure-object saves an lvalue reference for to each argument, regardless of its value category. Perfect forwarding still works; In fact, there isn't even a difference because named rvalue references would be lvalues anyway.
这篇关于在 lambda 中捕获完美转发的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 lambda 中捕获完美转发的变量
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
