【发布时间】:2014-08-22 10:09:40
【问题描述】:
以下签名被声明为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);
那么这就是编译器使用T = int& 实例化foo_as_always 的方式:
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);
然后编译器用T = int实例化foo_as_always:
int&& foo_as_always(int&& t)
{
// Does it call the second signature of std::forward(int&&)?
return std::forward<int>(t);
}
在这两种情况下,t 变量在任何表达式中都是左值。编译器如何知道std::forward函数的哪个重载必须被调用?
【问题讨论】:
标签: c++ templates c++11 perfect-forwarding