0

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

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

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

4

1 回答 1

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

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

于 2013-11-09T06:07:22.697 回答