为什么std :: forward()没有推断出类型?

时间:2014-08-29 15:47:40

标签: c++ c++11 reference rvalue

以下是代码。为什么如果我将typename remove_reference<S>::type&替换为S&,它将无法正常工作? (我的意思是推断出一种错误的类型)

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

如果我传递左值(int&&int将推断为Sint&的类型为aint& & ->int&返回forward()。一切运作良好,为什么我们需要int& &&->int&

remove_reference

1 个答案:

答案 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;

处理右值。