在lambda中完美地捕获完美的转发器(通用引用)

Perfectly capturing a perfect forwarder (universal reference) in a lambda

本文关键字:完美 转发器 引用 lambda      更新时间:2023-10-16

所以我有一个完美的转发器,我想在lambda中适当地捕获它,这样r值被复制进来,l值被引用捕获。然而,简单地使用std::forward并不能完成这项工作,如下代码所示:

#include<iostream>
class testClass
{
public:
   testClass() = default;
   testClass( const testClass & other ) { std::cout << "COPY C" << std::endl; }
   testClass & operator=(const testClass & other ) { std::cout << "COPY A" << std::endl; }
};
template< class T>
void testFunc(T && t)
   { [test = std::forward<T>(t)](){}(); }
int main()
{
   testClass x;
   std::cout << "PLEASE NO COPY" << std::endl;
   testFunc(x);
   std::cout << "DONE" << std::endl;
   std::cout << "COPY HERE" << std::endl;
   testFunc(testClass());
   std::cout << "DONE" << std::endl;
}

编译
g++ -std=c++14 main.cpp

产生输出

PLEASE NO COPY
COPY C
DONE
COPY HERE
COPY C
DONE

在完美的情况下,我希望只有"COPY C"出现在右值情况下,而不是左值情况下。

我的工作将是使用一个辅助函数重载L-和R-值,但我想知道是否有更好的方法。

干杯!

您可以使用以下命令:

[test = std::conditional_t<
             std::is_lvalue_reference<T>::value,
             std::reference_wrapper<std::remove_reference_t<T>>,
             T>{std::forward<T>(t)}]

现场演示

但是提供帮助函数似乎更容易读