【问题标题】:Is it possible to construct a general procedure for determing whether a binary operation causes overflow?是否可以构造一个通用过程来确定二进制操作是否会导致溢出?
【发布时间】:2015-03-25 22:32:13
【问题描述】:

我很好奇,是否可以编写一个包罗万象的实现,例如

template <typename T> 
bool overflows(T a, T b)
{
  // ... Returns true or false depending on whether a+b overflows
}

??????

如果没有,至少有人可以告诉我如何编写一个实现

   bool overflows (unsigned int a, unsigned int b)
   {
       // ... returns true or false depending on whether a+b > ~0
   }

???

由于我没有计算机科学学位,因此我没有接受过关于程序应该如何处理溢出的任何正规教育,尽管我了解溢出的概念(如果我们的数字范围是 0, 1,...,127,那么 + 操作在 64+64、65+63、66,62 等上“不起作用”

【问题讨论】:

  • a+b 不是&gt;~0 的唯一值是~0 本身。 ;) 无符号算术定义为 mod 2^n 用于 C++ 中保证的一些 n。带符号的算术......远没有保证。
  • 在浮点中,“a+ b 溢出”被定义为“a + b == +inf”。我不知道你还想要什么。但是你的~0让我觉得你对浮点不感兴趣,那么你应该选择一些你感兴趣的标签。
  • 我不知道这个问题的答案,但我会探索decltype。它返回对象的类型。从对象的类型,您可以推断出它可以正确存储的最大值。根据最大值,您可以推断给定操作是否会溢出。

标签: c++ floating-point overflow addition


【解决方案1】:

由于您只询问加法,您可以对定义了numeric_limits&lt;T&gt;::max() 的类型以及ab 中至少一个为非负数的附加假设进行此操作。 (可能有一种解决方法,但我没有看到简洁的方法。)

template <typename T> 
bool overflows(T a, T b)
{
  if(a < b) return overflows(b,a);
  //Since we assumed at least one is non-negative, this now makes sense.
  return b < std::numeric_limits<T>::max() - a;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多