爲什麼下面的代碼有效:爲什麼完美的轉發功能必須被模板化?
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