是否可以构造一个通用程序来判断二元运算是否会导致溢出?

Is it possible to construct a general procedure for determing whether a binary operation causes overflow?

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

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,则 + 运算不会 "work" 在 64+64、65+63、66,62 等上)

由于您只询问加法,因此您可以针对定义了 numeric_limits<T>::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;
}