I've just stumbled upon that T&&
in class and function means different things.
In function:
template<class T> void f(T&& t){}; // t is R or L-value
...
int i=0;
f(i); // t in f is lvalue
f(42); // t in f is rvalue
In class:
template<class T>
struct S {
S(T&& t){} // t is only R-value?
};
...
int i;
S<int> ss(i); // compile error - cannot bind lvalue to ‘int&&’
Does this means that if we haveT&& t
in class, than t
will be only rvalue?
Can some one point me where I can get more info about this?
Does it means that I need to write two method overloads for L and R-values?
ANSWER
As Alf's example shows, t
in function and class can be Lvalue or Rvalue.
In your function T
is deduced from the actual argument. The main use for that particular combination is perfect forwarding. In the class template T
is not deduced, it must be specified.
E.g., this compiles nicely with both g++ and msvc:
template<class T>
struct S {
S(T&& t){}
};
int main()
{
int i;
S< int& > ss(i);
}