以下是代码。为什么如果我将typename remove_reference<S>::type&
替换为S&
,它将无法正常工作? (我的意思是推断出一种错误的类型)
如果我传递一个右值(让int为int),那么S
将被推断为int
,a
的类型为int&
,{{1} }返回forward()
(右值)。
如果我传递左值(int&&
)int
将推断为S
,int&
的类型为a
,int& & ->int&
返回forward()
。一切运作良好,为什么我们需要int& &&->int&
?
remove_reference
答案 0 :(得分:7)
考虑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
实际上是一对重载 - 你所引用的重载只接受左值,并且
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;
处理右值。