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 中捕获完美转发的变量
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
