问题
template<class U>
void f( U && v)
{
std::cout << typeid(v).name() << "\n"; //'int' in both cases
if( boost::is_same<int&&,U>::value )
{
std::cout << "reach here\n"; //only with f<int&&>(int(1));
}
}
int main()
{
f(int(1));
f<int&&>(int(1));
std::cin.ignore();
}
Why v parameter is interpreted as int
when I don't explicitly use f<int&&>
?
What is the difference ? (Compiled with MVS2010)
My guess is that First is passed as a rvalue and second as a rvalue reference and both bound correctly into a rvalue reference, am I right ?
Thanks.
回答1:
No, not really. An rvalue reference is never deduced. The notion U&&
with U
being a deducible template parameter is used to indicate that U
should be deduced such that the rvalue-ness of the argument is retained:
- when passing an rvalue of type
X
the type ofU
becomesX
. - when passing a cv qualified lvalue of type
X
thenU
becomes the typeX cv&
.
The more interesting question is what happened to the rvalue references explicitly specified in the second call because there is no deduction going on because in this case the two rvalue references are collapsed into just one.
回答2:
First variant
f(int(1)) <=> f<int>(int(1)) <=> U==int <=> is_same<int&&,int> == false
Second variant
f<int&&>(int(1)) <=> U==int&& is_same<int&&,int&&> == true
Like this
来源:https://stackoverflow.com/questions/8842312/rvalue-reference-template-deduction