看來,要測試常量,必須測試模板參數,但要測試右值,必須測試實際參數。 (這是使用VC++ 2012.)這段代碼說明了我的意思:澄清通緝。 C++ type_traits
#include <type_traits>
#include <string>
#include <iostream>
using namespace std;
template<class T>
void f(T& x) {
cout << "f() is_const<T> and is_const<decltype<x)>" << endl;
cout << is_const<T>::value << endl; // Prints 1 when arg is const
cout << is_const<decltype(x)>::value << endl; // Prints 0 when arg is const
}
template<class T>
void g(T&& x) {
cout << "g() is_const<T> and is_const<decltype<x)>" << endl;
cout << is_const<T>::value << endl; // Prints 0 when arg is const
cout << is_const<decltype(x)>::value << endl; // Prints 0 when arg is cons
cout << "g() is_rvalue_reference<T> and is_rvalue_reverence<decltype(x)>" <<endl;
cout << is_rvalue_reference<T>::value << endl; // Prints 0 when arg is rvlaue
cout << is_rvalue_reference<decltype(x)>::value << endl; // Prints 1 when arg is rvalue
}
int main()
{
const std::string str;
f(str); // const argument
cout << endl;
g(std::string("")); // rvalue argument
return 0;
}
我很努力地理解這是爲什麼。有人可以解釋,或者指給我一篇解釋它的文章嗎?如果需要,我將深入研究C++ 11標準。任何人都知道有關的部分?
'const'是*型*的一部分。 「Rvalue」是一個值類別,它是*表達式*的一部分。兩件不同的事情。 –