整数幂函数:检测整数溢出?

时间:2013-11-09 05:19:06

标签: c++ integer metaprogramming template-meta-programming integer-overflow

考虑以下计算整数整数幂的元函数:

template <std::intmax_t Base, std::intmax_t Exponent> 
struct integer_power 
{
    static constexpr std::intmax_t temporary = integer_power<Base, Exponent/2>::value;
    static constexpr std::intmax_t value = temporary*temporary*(Exponent%2 == 1 ? Base : 1);
    static constexpr bool overflow = /* something */;
};

template <std::intmax_t Base> 
struct integer_power<Base, 0> 
{
    static constexpr std::intmax_t value = 1;
    static constexpr bool overflow = false;
};

当结果无法存储在整数中时,我希望内部变量溢出为真。怎么做?

1 个答案:

答案 0 :(得分:0)

嗯......你知道临时的,Base,你可以知道前一个级别是否溢出。我会从

开始
template <std::intmax_t Base, std::intmax_t Exponent>
struct integer_power {
  typedef integer_power<Base, Exponent/2> half_power;
  static constexpr std::intmax_t temporary = half_power::value;
  static constexpr std::intmax_t value = temporary * temporary * (Exponent % 2 == 1 ? Base : 1);
  static constexpr bool overflow = half_power::overflow ? true :
      (temporary >
       std::numeric_limits<intmax_t>::max() / 
           ( temporary * (Exponent % 2 == 1 ? Base : 1)) ? true : false);
};

(我没有对此进行过测试,并且大多数都是从头顶开始写的)