Namespaces
Variants

std::numeric_limits<T>:: traps

From cppreference.net
Utilities library
static const bool traps ;
(C++11 前)
static constexpr bool traps ;
(C++11 起)

对于所有算术类型 T ,若其在程序启动时至少存在一个值,在作为算术运算参数使用时会产生 陷阱 ,则 std:: numeric_limits < T > :: traps 的值为 true

目录

标准特化

T std:: numeric_limits < T > :: traps 的值
/* non-specialized */ 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 输出:
bool:     traps = true
char:     traps = true
char16_t: traps = true
long:     traps = true
float:    traps = false
// Clang 输出:
bool:     traps = false
char:     traps = true
char16_t: traps = true
long:     traps = true
float:    traps = false

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 497 C++98 未明确说明在运行时启用或禁用捕获时的返回值 返回程序启动时的启用状态

参见

浮点环境
标识在舍入前检测微小值的浮点类型
(公开静态成员常量)
标识将精度损失检测为非规范化损失而非不精确结果的浮点类型
(公开静态成员常量)