std::numeric_limits::is_modulo

static const bool is_modulo;
(C++11 前)
static constexpr bool is_modulo;
(C++11 起)

std::numeric_limits<T>::is_modulo 对所有以模算术处理溢出,即若此类型的加法、减法、乘法或除法结果会落在范围 [min(), max()] 外,则这种运算返回的结果与期望值相差 max()-min()+1 整数倍,的算术类型 Ttrue

目录

标准特化

T std::numeric_limits<T>::is_modulo 的值
/* non-specialized */ false
bool false
char 实现定义
signed char 实现定义
unsigned char true
wchar_t 实现定义
char16_t 实现定义
char32_t 实现定义
short 实现定义
unsigned short true
int 实现定义
unsigned int true
long 实现定义
unsigned long true
long long 实现定义
unsigned long long true
float false
double false
long double false

注意

尽管 C++11 标准仍然说“在大多数机器上,这对于有符号整数为真”,然而准确的措辞从 C++03 到 C++11 更改,使得 true 值不再与有符号整数溢出上的未定义行为(它更改为对于严格要求的“可能”)兼容。因此,依赖于有符号溢出为未定义(为了优化机会)的实现现在对有符号整数设置 is_modulofalse 。见示例 GCC PR 22200

LWG 问题 2422 期待修改标准措辞为“ is_modulo 对有符号整数类型为 false ,除非实现定义有符号整数溢出为回绕”。

示例

演示模类型的行为

#include <iostream>
#include <type_traits>
#include <limits>
 
template<class T>
typename std::enable_if<std::numeric_limits<T>::is_modulo>::type
    check_overflow()
{
    std::cout << "\nmax value is " << std::numeric_limits<T>::max() << '\n'
              << "min value is " << std::numeric_limits<T>::min() << '\n'
              << "max value + 1 is " << std::numeric_limits<T>::max()+1 << '\n';
}
 
int main()
{
    check_overflow<int>();
    check_overflow<unsigned long>();
    // check_overflow<float>(); // 编译时错误,非模类型
}

可能的输出:

max value is 2147483647
min value is -2147483648
max value + 1 is -2147483648
 
max value is 18446744073709551615
min value is 0
max value + 1 is 0

参阅

[静态]
鉴别整数类型
(公开静态成员常量)
[静态]
鉴别 IEC 559/IEEE 754 浮点类型
(公开静态成员常量)
[静态]
鉴别准确表示的类型
(公开静态成员常量)

版本历史

  • (当前 | 先前 2017年6月9日 (五) 23:58Fruderica讨论 | 贡献. . (3,397字节) (+335). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:17P12bot讨论 | 贡献 . . (3,062字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:47P12bot讨论 | 贡献 . . (3,062字节) (-322). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 15:02P12bot讨论 | 贡献 . . (3,384字节) (+337). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 12:12P12讨论 | 贡献 . . (3,047字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (3,047字节) (-25). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:54P12讨论 | 贡献 . . (3,072字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (3,072字节) (+3,072). . (Translated from the English version using Google Translate)