mardi 5 janvier 2016

Number of value representation bits in a integer, according to the standard?

Consider the following helper structs:

template <class T>
struct bit_count_1:
std::integral_constant<
    std::size_t,
    std::numeric_limits<typename std::make_unsigned<T>::type>::digits
> {};

template <class T>
struct bit_count_2:
std::integral_constant<
    std::size_t,
    std::numeric_limits<T>::digits + std::is_signed<T>::value
> {};

template <class T>
constexpr std::size_t compute_bit_count() {
    using type = typename std::make_unsigned<T>::type;
    constexpr type zero = 0;
    constexpr type one = 1;
    constexpr type max = ~zero;
    type current = max;
    std::size_t i = 0; 
    while (current) {
        current >>= one;
        ++i;
    }
    return i;
}

template <class T>
struct bit_count_3:
std::integral_constant<
    std::size_t,
    compute_bit_count<T>()
> {};

For every integral type T such that std::is_integral<T>::value is true except bool do I have the guarantee, by the standard, that:

  • bit_count_1, bit_count_2 and bit_count_3 have the same value N
  • static_cast<T>(1) << (N - 1) is well defined
  • ~static_cast<T>(0) >> (N - 1) is well defined

I am currently working on a C++ proposal, so I need to be sure whether this is true according to the standard, or not, and for the moment it's a little unclear for me.

Aucun commentaire:

Enregistrer un commentaire