在lambda中完美地捕获完美的转发器(通用引用)
Perfectly capturing a perfect forwarder (universal reference) in a lambda
所以我有一个完美的转发器,我想在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)}]
现场演示
但是提供帮助函数似乎更容易读
相关文章:
- 试试完美的正方形,你能给点小费吗
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 不计算一个范围内的完美数
- 完美前进使用 std::forward vs RefRefCast
- 如何编写一个完美的缩写函数模板?
- 将函数参数完美转发到函数指针:按值传递呢?
- C++20理念:要求表达和完美转发
- 完美的转发和构造函数
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 完美的广场与位明智和
- 返回值的完美转发?
- 使用衰减与完美转发
- 可变参数模板:将整数参数完美转发到 lambda
- 完美转发C++重载和模板化函子及其参数
- 在完美转发中需要衰减
- C++完美转发:如何避免悬空引用
- 完美的对象转发阵列
- "删除"在 g++ 中抛出错误,同时在 clang 中完美编译
- 无法理解一段具有完美转发和省略号的C++代码
- 在lambda中完美地捕获完美的转发器(通用引用)