Domanda

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?

È stato utile?

Soluzione

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)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top