以下签名被声明为std::forward
重载:
template<class T> T&& forward(typename remove_reference<T>::type& arg) noexcept;
template<class T> T&& forward(typename remove_reference<T>::type&& arg) noexcept;
现在,考虑以下模板函数:
template<class T> T&& foo_as_always(T&& t)
{
return std::forward<T>(t);
}
如果我写:
int i = 0;
foo_as_always(i);
然后这就是编译器实例化foo_as_always
的方式T = int&
:
int& foo_as_always(int& t)
{
// Does it call the first signature of std::forward(int&)
return std::forward<int&>(t);
}
如果我写:
foo_as_always(0);
然后编译器实例foo_as_always
化T = int
:
int&& foo_as_always(int&& t)
{
// Does it call the second signature of std::forward(int&&)?
return std::forward<int>(t);
}
在这两种情况下,t
变量在任何表达式中都是左值。编译器如何知道std::forward
必须调用函数的哪个重载?