为什么 std::forward() 不推断类型?

Why std::forward() doesn't deduce type?

本文关键字:类型 std forward 为什么      更新时间:2023-10-16

下面是代码。为什么如果我用S&替换typename remove_reference<S>::type&,它不会很好地工作?(我的意思是一种类型会被推断错误)

如果我传递一个右值(让int为int),那么S将被推导为inta的类型是int&forward()返回int&&(右值)。

如果我传递一个左值(int),则S将被推导为int&a的类型为int& & ->int&forward()返回int& &&->int&。一切都很好,为什么我们需要remove_reference

template<class S>
S&& forward(typename remove_reference<S>::type& a) noexcept
{
  return static_cast<S&&>(a);
} 

考虑forward:的原始用例

template<class T>
void f(T&& t) { g(std::forward<T>(t)); }

t有一个名称,所以它是f中的一个左值,即使它绑定到一个右值。如果允许forward推导类型,那么人们会很想写std::forward(t),但实际上并没有得到他们期望的完美转发。


此外,你的分析也不正确。template<class S> void f(S& t);不与右值结合。std::forward实际上是一对重载——您所指的那个重载只取lvalues,而

template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

处理右值。

相关文章: