问题描述
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 中捕获完美转发的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)