需要澄清.C++ type_traits
Clarification wanted re. C++ type_traits
似乎
要测试恒定性,必须测试模板参数,但要测试右值性,必须测试实际参数。(这是使用 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;
}
我很难理解为什么会这样。有人可以解释,或者指出我解释它的文章吗?如果需要,我将深入研究C++11标准。有人知道相关部分吗?
原因是你误解了事情。 在任何这些示例中,x
都不会const
,仅仅是因为没有const
引用类型(无论如何都无法更改引用的内容)。在is_const<T>
中,您基本上忽略了您将x
声明为T&
。
类似的误解也发生在右值参考测试中。T&&
中的T
(称为通用引用,顺便说一句)将在传递左值时推导出为U&
,传递右值时推导出为U
。在测试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
相关文章:
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 控制到达非空函数clang(-Wreturn-type)的末尾
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 将系数存储在头文件的数组中("does not name a type"错误)
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 在"结构提升::enable_if<提升::is_pod<T>,无效>"中没有名为"type"的类型
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- OpenCV CV_16F type
- C++ "错误:在'类 std::result_of< ... >"中没有名为'type'的类型"
- 将内存分配返回值强制转换为 TYPE 数组
- C++ 一个lambda浅拷贝const Type&如果它被赋予一个命名捕获,如[copy=val](){}?
- reference_wrapper导致"incomplete type is not allowed"
- 继承类时"invalid use of incomplete type ‘class tree_node_t’"
- 由于"error C4430: missing type specifier - int assumed. Note: C++ does not support default-int",我现在无法编
- cv::D ataType<> 与 cv::traits::Type<>