I'm trying to understand rvalue
references. I have seen how they are used in constructors, with things like std::move
and std::forward
, but I still don't understand why this doesn't work:
void func(string&& str)
{
cout << str << endl;
}
int main(int argc, char* argv[])
{
string s("string");
func(s);
}
And this does:
template<typename T>
void func(T&& str)
{
cout << str << endl;
}
int main(int argc, char* argv[])
{
string s("string");
func(s);
}
Why does it work with the function template version?
T
is deduced to bestring&
. "When the function parameter type is of the form T&& where T is a template parameter, and the function argument is an lvalue of type A, the type A& is used for template argument deduction." Usestd::move
if you want the former to work. – AllegraallegrettoT
can be deduced to a reference type. Normally in template type deductionT
is only deduced as a non-reference. – Cop