为什么下面的代码有效:为什么完美的转发功能必须被模板化?
template<typename T1>
void foo(T1 &&arg) { bar(std::forward<T1>(arg)); }
std::string str = "Hello World";
foo(str); // Valid even though str is an lvalue
foo(std::string("Hello World")); // Valid because literal is rvalue
但不是:
void foo(std::string &&arg) { bar(std::forward<std::string>(arg)); }
std::string str = "Hello World";
foo(str); // Invalid, str is not convertible to an rvalue
foo(std::string("Hello World")); // Valid
为什么不例子2中,左值获得同样的方式,它并实例1中得到解决?
此外,为什么标准认为需要在std :: forward中提供参数类型而不是简单地推导它呢?无论何种类型,简单地向前转就显示意图。
如果这不是一个标准的东西,只是我的编译器,我使用msvc10,这将解释蹩脚的C++ 11支持。
感谢
编辑1:更改文字的 “Hello World” 进行的std :: string( “Hello World” 的),使右值。
酒吧会发生什么?编译并不意味着它是必须的。我相信它应该分别为'void foo(T1&arg)'和'void foo(std :: string&arg)'。 – AJG85
“Hello World”不是一个右值,它是一个类型为const char [12]的左值。 – GManNickG
@ AJG85酒吧里发生的事情并不重要。 &&表示右值引用。 – Mranz