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