문제

Consider the following metafunction that computes the integer power of an integer:

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

I would like the internal variable overflow to be true when the result cannot be stored in an integer. How to do that?

도움이 되었습니까?

해결책

Well... you know temporary, Base, and you can know whether the previous level was an overflow. I'd start with something like

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

(I haven't tested that, and mostly wrote it off the top of my head)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top