在 lambda 中捕获完美转发的变量

2021-12-23 00:00:00 lambda c++ c++11 c++14 perfect-forwarding
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.

相关文章