【问题标题】:Integer power metafunction: detect integer overflow?整数幂元函数:检测整数溢出?
【发布时间】:2013-11-09 05:19:05
【问题描述】:

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

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;
};

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

【问题讨论】:

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


    【解决方案1】:

    嗯...你知道临时的,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);
    };
    

    (我还没有测试过,大部分都是在我的脑海中写出来的)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多