使用 std::forward 的主要目的是什么以及它解决了哪些问题?

新手上路,请多包涵

在完美转发中, std::forward 用于将命名的右值引用 t1t2 转换为未命名的右值引用。这样做的目的是什么?如果我们将 t1 & t2 作为左值,这将如何影响被调用的函数 inner

 template <typename T1, typename T2>
void outer(T1&& t1, T2&& t2)
{
    inner(std::forward<T1>(t1), std::forward<T2>(t2));
}

原文由 Steveng 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 512
1 个回答

从另一个角度来看,在通用引用赋值中处理 右值 时,可能需要保持变量的类型不变。例如

auto&& x = 2; // x is int&&

auto&& y = x; // But y is int&

auto&& z = std::forward<decltype(x)>(x); // z is int&&

使用 std::forward ,我们确保 zx 具有完全相同的类型。

此外, std::forward 不影响左值引用:

 int i;

auto&& x = i; // x is int&

auto&& y = x; // y is int&

auto&& z = std::forward<decltype(x)>(x); // z is int&

仍然 z x 相同的类型。

So, back to your case, if the inner function has two overloads for int& and int&& , you want to pass variables like z assignment not y 一。

示例中的类型可以通过以下方式评估:

 std::cout<<is_same_v<int&,decltype(z)>;
std::cout<<is_same_v<int&&,decltype(z)>;

原文由 Sorush 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题