一、数值的极值概述
- 数值类型有着与平台相依的极值
- C++标准规定了各种类型必须保证的最小精度。这些最小值如下图所示:
类型 | 最小长度 |
char | 1byte(8bits) |
shortint | 2bytes |
int | 2bytes |
longint | 4bytes |
longlongint | 8bytes |
float | 4bytes |
double | 8bytes |
longdouble | 8bytes |
二、numeric_limits
- 传统C语言使用预处理器常量来决定数值的极值,其中整数常量定义于<climits>或<limits.h>中,浮点常量定义于<cfloat>或<float.h>中
- C++标准库定义一个template numeric_limits来提供这些常值
- 使用numeric_limits有优点:
- 第一个是提供更好的类型安全性
- 第二个是程序员可以借此写出一些template以核定这些极值
- 使用numeric_limits可以很轻松的写出跨平台的程序
三、numeric_limits的实现
- numeric_limits实现有两种:
- 一种是通用性的模板,其提供很多接口,是每个类型都共用的
- 一种是特化版本的,每特定的类型特例化
- 这里把成员is_specialized设为false,意思为对于类型T而言,不存在所谓的极值
特化版本的numeric_limits
- 各具体类型的极值,由特化版本提供。定义如下:
- 这里把is_specialized设为true,所有其他成员都根据特定类型的具体极值而设定
- 特化版本涵盖所有数值基础类型,包括:bool、char、signed char、unsigned char、char16_t、char32_t、wchar_t、short、unsigned short、int、unsigned int、long、unsigned long、long long、unsigned long long、float、double、long double
- 当然你也可以为自己定义的数值类型定义一份特例化
四、numeric_limits提供的操作
- numeric_limits定义在<limits>头文件中,下图列出了所有成员及其意义,最右侧对应的是C常量
- C++11前并不提供lowest()和max_digits10,且所有成员函数不提供noexcept
所有成员都是constexpr的
- 从C++11起,所有成员都被声明为constexpr的
- 例如你可以在需要编译期表达式的地方使用max():
- static const int ERROR_VALUE = std::numeric_limits<int>::max();
- float a[std::numeric_limits<short>::max()];
round_style、has_denorm
- round_style的值如下图所示:
舍/入风格 | 意义(译注:以下说明中的y为“被操作数") |
round_toward_zero | 无条件舍去(译注:就是truncate) |
round_to_nearest | 化为最接近值(译注:就是四舍五人) |
round_toward_infinity | 化为不小于y之最小整数 ceiling) |
round_toward_neg_infinity | 化为不大于y之最大整数 |
round_indeterminate | 无法确定 |
五、numeric_limits使用示例
演示案例1
- 查看各种数据类型的最大值
- cout << "max(short)" << numeric_limits<short>::max() << endl;
- cout << "max(int)" << numeric_limits<int>::max() << endl;
- cout << "max(long)" << numeric_limits<long>::max() << endl << endl;
- cout << "max(float)" << numeric_limits<float>::max() << endl;
- cout << "max(double)" << numeric_limits<double>::max() << endl;
- cout << "max(long double)" << numeric_limits<long double>::max() << endl << endl;
- x64编译器下结果如图所示
演示案例2
- 下面查看char类型是否带有正负号,string类型是否带有极值