Namespaces
Variants

std::numeric_limits<T>::traps

来自 zh.cppreference.net
 
 
 
类型支持
基本类型
定宽整数类型 (C++11)
定宽浮点数类型 (C++23)
(C++11)    
(C++17)
数值极限
C 数值极限接口
运行时类型信息
 
 
static const bool traps;
(C++11 前)
static constexpr bool traps;
(C++11 起)

值 std::numeric_limits<T>::traps 对以下所有算术类型 true 为 T:这些类型在程序启动时至少有一个值,若将该值用作算术运算的参数,则会生成陷阱。

标准特化

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 未明确说明在运行时启用或禁用捕获时的返回值 返回程序启动时的启用状态

参见

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