Function population_count

Synopsis

#include "breeze/mathematics/population_count.hpp"

template <typename T>
constexpr int population_count(T t) noexcept

Description

Returns the number of on bits in the binary representation of the value of t.

T must be an unsigned integral type.

Warning
[FUTURE] This function template will be removed in favor of std::popcount() when Breeze will require C++20.

Mentioned in

Source

Lines 53-88 in breeze/mathematics/brz/population_count.tpp. Line 34 in breeze/mathematics/population_count.hpp.

template< typename T >
constexpr int
population_count( T t ) noexcept
{
    using namespace population_count_private ;

    static_assert( ! has_sign< T >::value, "" ) ;

    int                 count = 0 ;
    while ( t != 0 ) {
        count += count_table[ t & ( ( 1u << table_width ) - 1 ) ] ;

    //      Clang gives a -Wshift-count-overflow warning on this when
    //      `T` is `unsigned char`, apparently ignoring the fact that
    //      `t` is promoted.
    //
    //      (Problem encountered with Clang 5.0.1.)
    //
    //      GCC, instead, complains about a conversion from `int` to
    //      `unsigned char` :-(
    //
    //      (Problem encountered with GCC 9.3.0.)
    // -----------------------------------------------------------------------
#   pragma clang diagnostic push
#   pragma clang diagnostic ignored "-Wshift-count-overflow"

#   pragma GCC diagnostic push
#   pragma GCC diagnostic ignored "-Wconversion"
    // -----------------------------------------------------------------------
        t >>= table_width ;

#   pragma GCC diagnostic pop
#   pragma clang diagnostic pop
    }
    return count ;
}