Getting number of ones in a number in compile-time

A

Alex Vinokur

I wrote the following code to get number of ones in a number in
compile-time.

Calling function is
static_get_number_of_ones<std::size_t, 17>().
static_get_number_of_ones<int, 17>()
static_get_number_of_ones<long, 17>().

I would like the static_get_number_of_ones() function to have default
value for typename T, but 'typename T' is first in the list of
arguments.

Is it possible to do that in other way?

// -----------------------------------
#include <iostream>

template <typename T, T N, int S = sizeof(T) & CHAR_BIT>
struct static_number_of_ones
{
static const T m_value = static_number_of_ones<T, N, S -
1>::m_value >> 1;
static const int m_count = static_number_of_ones<T, N, S -
1>::m_count + (static_number_of_ones<T, N, S - 1>::m_value & 0x1);
};

template <typename T, T N>
struct static_number_of_ones<T, N, 0>
{
static const T m_value = N;
static const int m_count = 0;
};

template <typename T, T N>
std::size_t static_get_number_of_ones()
{
return static_number_of_ones<T, N>::m_count;
}


int main()
{

std::cout << static_get_number_of_ones<std::size_t, 17>() <<
std::endl;
return 0;

}
// ------------------------------

Alex Vinokur
 
A

Alex Vinokur

I wrote the following code to get number of ones in a number in
compile-time.

Calling function is
static_get_number_of_ones<std::size_t, 17>().
static_get_number_of_ones<int, 17>()
static_get_number_of_ones<long, 17>().

I would like the static_get_number_of_ones() function to have default
value for typename T, but 'typename T' is first in the list of
arguments.

Is it possible to do that in other way?

Something like:
template <std::size_t N>
std::size_t static_get_number_of_ones()
{
// -----------------------------------
#include <iostream>

template <typename T, T N, int S = sizeof(T) & CHAR_BIT>
struct static_number_of_ones
{
  static const T   m_value = static_number_of_ones<T, N, S -
1>::m_value >> 1;
  static const int m_count = static_number_of_ones<T, N, S -
1>::m_count + (static_number_of_ones<T, N, S - 1>::m_value & 0x1);
std::cout said:
};

template <typename T, T N>
struct static_number_of_ones<T, N, 0>
{
  static const T   m_value = N;
        static const int m_count = 0;

};

template <typename T, T N>
std::size_t static_get_number_of_ones()
{
        return static_number_of_ones<T, N>::m_count;

}

int main()
{

  std::cout << static_get_number_of_ones<std::size_t, 17>() <<
std::endl;
        return 0;

}

// ------------------------------

Alex Vinokur
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top