【发布时间】:2013-01-18 13:15:35
【问题描述】:
C++11 提供了两种类型特征模板类:std::is_integer 和 std::is_integral。但是,我无法分辨它们之间的区别。
什么类型,比如说T,可以使std::is_integer<T>::value为真,使std::is_integral<T>::value为假?
【问题讨论】:
标签: c++ c++11 language-lawyer typetraits
C++11 提供了两种类型特征模板类:std::is_integer 和 std::is_integral。但是,我无法分辨它们之间的区别。
什么类型,比如说T,可以使std::is_integer<T>::value为真,使std::is_integral<T>::value为假?
【问题讨论】:
标签: c++ c++11 language-lawyer typetraits
std::is_integer<T> 不存在。
话虽如此,std::numeric_limits<T>::is_integer 确实存在。
我不知道std::numeric_limits<T>::is_integer 和std::is_integral<T> 之间有任何显着差异。后者设计得晚得多,并在 C++11 中成为标准,而前者是在 C++98 中引入的。
【讨论】:
对于std::is_integral<T>::value 和std::numeric_limits<T>::is_integer,没有任何类型T 具有不同的结果。引用draft Standard:
3.9.1 基本类型 [basic.fundamental]
7 种类型 bool、char、char16_t、char32_t、wchar_t 以及带符号和 无符号整数类型统称为整数类型。一种 整数类型的同义词是整数类型。[...]
18.3.2.4 numeric_limits 成员 [numeric.limits.members]
static constexpr bool is_integer;
17 如果类型是整数则为真。
20.9.4.1 主要类型类别 [meta.unary.cat](表 47)
template <class T> struct is_integral;
T 是整数类型 (3.9.1)
【讨论】:
std::is_integral_v<T> 只会对内置整数返回 true。
该标准允许对std::numeric_limits<T>::is_integer 进行专门化,并为boost::multiprecion::cpp_int 等自定义整数类型返回true。
【讨论】:
Checks whether T is an integral type. Provides the member constant value which is equal to true, if T is the type bool, char, char16_t, char32_t, wchar_t, short, int, long, long long, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants. Otherwise, value is equal to false. 中的implementation-defined 意味着应用程序可以像std::numeric_limits 一样为std::is_integral 注入特化?
std::is_integral<T> 和 std::numeric_limits<T>::is_integer 不一样。例如。 boost::multiprecision 大整数的处理方式不同。
这是来自相应的问题:
is_integral返回有关类型性质的信息,并且是 仅适用于“本机”整数类型,它永远不应该适用于 类类型。也就是说is_integer和is_class是相互的 独家。
numeric_limits另一方面返回关于 一个类型的行为——如果你对一个特定的概念建模 will - 因此应该专门用于 UDT。注意专精is_integer用于 UDT 会破坏代码,因为is_integer意味着 很多其他事情也是如此,比如微不足道的移动/复制/初始化 等等
【讨论】:
不同之处在于std::is_integral<T>将只识别十进制整数,包括boolcharchar16_tchar32_twchar_tshortintlonglong long。而std::numeric_limits<T>::is_integer 将识别所有这些以及float double。查看这两个页面了解更多信息:is_integer、is_integral
【讨论】: