[英]How to make compiler know which overload of a function to call to avoid ambiguity?
[英]How does the compiler know that which overload of std::forward function has to be called?
以下签名声明为std::forward
overloads:
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
变量在任何表达式中都是l值。 编译器如何知道必须调用std::forward
函数的哪个重载?
因为你明确地提供了模板参数(你提供的是<T>
); 没有类型扣除。
在调用foo_as_always(i);
, i
是一个左值,所以T
推导为int &
,这就是你为std::forward
。
在调用foo_as_always(0);
, 0
是一个rvalue,因此T
推导为int
,这也是你为std::forward
。
在这两种情况下,它最终都会调用第一个重载,当然,因为t
是左值,正如你所说的那样。 但返回类型不同 - 在第一种情况下,它是int& &&
,所以int&
,在第二种情况下,它是int &&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.