gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:52:28 28 4
gpt4 key购买 nike

所以我有一个完美的转发器,我想在 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)}]

Live Demo

但提供辅助函数似乎更具可读性

关于c++ - 在 lambda 中完美捕获完美的转发器(通用引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410209/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com