在lambda中完美捕获完美的货运代理(通用参考) [英] Perfectly capturing a perfect forwarder (universal reference) in a lambda

查看:63
本文介绍了在lambda中完美捕获完美的货运代理(通用参考)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个完美的转发器,我想以lambda形式对其进行适当捕获,以便复制R值,并通过引用捕获L值.但是,仅使用std :: forward不能完成此工作,如以下代码所示:

So I have a perfect forwarder, and I want to appropriately capture it in a lambda, such that R-values are copied in, and L-values are captured by reference. However simply using std::forward doesn't do the job, as evidenced by this code:

#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",而不是在左值案例中出现.

In a perfect world, I would like to only have the "COPY C" appear in the rvalue case, not the lvalue case.

我的解决方法是使用对L-和R-值重载的辅助函数,但是我想知道是否有更好的方法.

My work around would be to use a helper function overloaded for L- and R- values, but I was wondering if there was a better way.

干杯!

推荐答案

您可以使用以下内容:

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

实时演示

但是提供助手功能似乎更具可读性

but providing helper function seems more readable

这篇关于在lambda中完美捕获完美的货运代理(通用参考)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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