1

I have simple template metaprogramming class to calculate the bits set of a number:

template <int x>
struct BitsSet {
    static const int n = BitsSet<(x >> 1)>::n + (x & 1);
};
template <>
struct BitsSet<0> {
    static const int n = 0u;
};

Which works fine, but I'd like the template to be more flexible on the type holding the number, for example:

template <typename T, T x>
struct BitsSet {
    static const T n = BitsSet<T, (x >> 1)>::n + (x & 1);
};
template <typename T>
struct BitsSet<T, 0> {
    static const int n = 0u;
};

However the error is:

significant.h:32:12: error: template argument ‘(T)0’ involves template parameter(s)
    32 |     struct BitsSet<T, 0> {

I belive that it fails given the point (5) of the description for partial specialization Am I right?

As well there are several questions relating to this error, I think this solution being the closest... but honestly I am not capable to reach a solution to my problem.

A simplier question would be: how do you parametrize the int type in the typical factorial template calculation?

urnenfeld
  • 1,030
  • 9
  • 25
  • 2
    For reference, this is often referred to as the "pop count" or Hamming weight of an integer, and is already available as [`std::popcount`](https://en.cppreference.com/w/cpp/numeric/popcount) – Brian61354270 Dec 11 '21 at 20:41
  • Relevant: [Are the results of bitwise operations on signed integers defined?](https://stackoverflow.com/q/11644362/11082165) – Brian61354270 Dec 11 '21 at 20:43
  • 1
    `std::popcount` is a [`constexpr`](https://en.cppreference.com/w/cpp/language/constexpr) function, which can be evaluated in constant expressions (i.e., at compile time). See [When does a constexpr function get evaluated at compile time?](https://stackoverflow.com/q/14248235/11082165) – Brian61354270 Dec 11 '21 at 20:54

0 Answers0