std::numeric_limits<T>::traps
来自 cppreference.cn
static const bool traps; |
(C++11 前) | |
static constexpr bool traps; |
(C++11 起) | |
对于所有算术类型 T
,如果该类型在程序开始时至少有一个值,在用作算术运算的参数时会生成陷阱(trap),则 std::numeric_limits<T>::traps 的值为 true。
目录 |
[编辑] 标准特化
T
|
std::numeric_limits<T>::traps 的值 |
/* 未特化 */ | false |
bool | false |
char | 通常为 true |
signed char | 通常为 true |
unsigned char | 通常为 true |
wchar_t | 通常为 true |
char8_t (C++20起) | 通常为 true |
char16_t (C++11起) | 通常为 true |
char32_t (C++11起) | 通常为 true |
short | 通常为 true |
unsigned short | 通常为 true |
int | 通常为 true |
unsigned int | 通常为 true |
long | 通常为 true |
unsigned long | 通常为 true |
long long (C++11起) | 通常为 true |
unsigned long long (C++11起) | 通常为 true |
float | 通常为 false |
double | 通常为 false |
long double | 通常为 false |
[编辑] 注意
在大多数平台上,整数除以零总是会产生陷阱,并且对于所有支持值 0 的整数类型,std::numeric_limits<T>::traps 为 true。唯一的例外是类型 bool:尽管除以 false 会因为从 bool 到 int 的整型提升而产生陷阱,但产生陷阱的是值为零的 int。零不是 bool 类型的值。
在大多数平台上,浮点异常可以在运行时开启和关闭(例如,Linux 上的 feenableexcept() 或 Windows 上的 _controlfp),在这种情况下,对于浮点类型,std::numeric_limits<T>::traps 的值反映了程序启动时浮点陷阱设施的状态,在大多数现代系统上该值为 false。一个例外是 DEC Alpha 程序,如果编译时没有使用 -ieee
选项,其值为 true。
[编辑] 示例
运行此代码
#include <iostream> #include <limits> int main() { std::cout << std::boolalpha << "bool: traps = " << std::numeric_limits<bool>::traps << '\n' << "char: traps = " << std::numeric_limits<char>::traps << '\n' << "char16_t: traps = " << std::numeric_limits<char16_t>::traps << '\n' << "long: traps = " << std::numeric_limits<long>::traps << '\n' << "float: traps = " << std::numeric_limits<float>::traps << '\n'; }
可能的输出
// GCC output: bool: traps = true char: traps = true char16_t: traps = true long: traps = true float: traps = false // Clang output: bool: traps = false char: traps = true char16_t: traps = true long: traps = true float: traps = false
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 497 | C++98 | 不清楚在运行时启用或禁用陷阱时返回什么 (同上) |
返回程序开始时的启用状态 (同上) |
[编辑] 参阅
浮点环境 | |
[静态] |
确定舍入前检测微小的浮点类型 (公开静态成员常量) |
[静态] |
确定将精度损失检测为非正规化损失而非不精确结果的浮点类型 (公开静态成员常量) |