請考慮下面的代碼:類型不推導爲r值參考:爲什麼不呢?
class CMyClass {};
template<class T>
void func(T&& param) {
if (std::is_same<CMyClass, std::decay<T>::type>::value)
std::cout << "param is a CMyClass\n";
if (std::is_same<T, CMyClass&>::value)
std::cout << "param is a CMyClass reference\n";
else if (std::is_same<T, CMyClass&&>::value)
std::cout << "param is a CMyClass r-value reference\n";
else if (std::is_same<T, const CMyClass&>::value)
std::cout << "param is a const CMyClass reference\n";
else if (std::is_same<T, const CMyClass&&>::value)
std::cout << "param is a const CMyClass r-value reference\n";
else if (std::is_same<T, const CMyClass>::value)
std::cout << "param is a constant CMyClass\n";
else if (std::is_same<T, CMyClass>::value)
std::cout << "param is a CMyClass\n";
else
std::cout << "param is not a CMyClass\n";
}
CMyClass mc3;
func(std::move(mc3));
從這個小程序的輸出
param is a CMyClass
param is a CMyClass
爲什麼MC3的類型不被推斷爲R值的參考嗎?
related/dupe:http://stackoverflow.com/questions/16373881/why-forwarding-reference-does-not-deduce-to-rvalue-reference-in-case-of-rvalue – NathanOliver
_「爲什麼有請問mc3的類型是否被推斷爲r值參考?「_因爲它不是一個? –
你的代碼檢查'T'的類型,但是然後打印出一個關於'param'類型的謊言。 'param'的類型是'T &&'不''T,所以你的程序在於。現在,你需要用什麼類型來代替'T'來使'T &&'等於'CMyClass &&'?那麼什麼是'T'? –