Jiv*_*son 1 c++ templates type-traits c++11
似乎要测试常量,必须测试模板参数,但要测试rvalue-ness,必须测试实际参数.(这是使用VC++ 2012.)这段代码说明了我的意思:
#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;
}
Run Code Online (Sandbox Code Playgroud)
我很难理解为什么会这样.有人可以解释,或指向我解释它的文章?如果需要,我将深入研究C++ 11标准.有人知道相关部分吗?
原因是你误解了事情.x永远不会出现const在任何这些例子中,仅仅是因为没有const引用类型(你无法改变引用引用的内容).在is_const<T>你基本上忽略你宣称x为T&.
rvalue ref测试也存在类似的误解.的T在T&&(其被称为通用参考,顺便说一句)将被推导出U&当传递一个左值和U当你通过一个rvalue.测试时is_rvalue_reference<T>,你又忽略了你声明x的T&&.在测试时is_const<T>,您没有考虑T将作为参考的事实,如上所述,它永远不会const.
正确的测试g将是
std::is_const<typename std::remove_reference<T>::type>::value 和std::is_rvalue_reference<T&&>::value