名稱空間
變體
操作

std::numeric_limits<T>::traps

來自 cppreference.com
< cpp‎ | 型別‎ | 數值限制
 
 
 
 
 
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>::trapstrue。唯一的例外是型別 bool:儘管除以 false 會因為從 boolint 的整型提升而產生陷阱,但產生陷阱的是值為零的 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 不清楚在執行時啟用或停用陷阱時返回什麼
(同上)
返回程式開始時的啟用狀態
(同上)

[編輯] 參閱

浮點環境
確定舍入前檢測微小的浮點型別
(公開靜態成員常量) [編輯]
確定將精度損失檢測為非正規化損失而非不精確結果的浮點型別
(公開靜態成員常量) [編輯]