在lambda中捕获完全转发的变量 [英] Capturing perfectly-forwarded variable in lambda

查看:94
本文介绍了在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?

EDIT:完全转发的变量是参数包?

推荐答案


使用
和& mStuff语法捕获完美转发的mStuff变量?

Is it correct to capture the perfectly-forwarded mStuff variable with the &mStuff syntax?

是,假设您不使用这个lambda外 doSomething 。您的代码捕获每个引用 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 每个引用。 closure-object保存每个参数的值,无论其值类别如何。完美的转发仍然工作;事实上,甚至没有什么区别,因为命名的右值引用总是左值。

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆