Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of std::bitset without instance

Given a typedef for a std::bitset of some size, I need to be able to determine that size at compile time. For example:

typedef std::bitset<37> permission_bits;
static_assert(permission_bits::size() == 37, "size must be 37");  // not valid

The above is a bit contrived, but shows the general problem.

As far as I can see in the standard, there is no static constexpr member of std::bitset that will let me extract the size. Have I missed something? And if not, what can I do to extract the size at compile time?

like image 872
marack Avatar asked Dec 11 '22 11:12

marack


2 Answers

Try:

template< typename > struct bitset_size;
template< std::size_t N > struct bitset_size< std::bitset< N > >
  : std::integral_constant< std::size_t, N > {};

and

static_assert( bitset_size<permission_bits>::value == 37, "size must be 37");
like image 67
Daniel Frey Avatar answered Dec 20 '22 06:12

Daniel Frey


You can make one up using template metaprogramming:

template<class>
struct bitset_traits;

template<size_t N>
struct bitset_traits< std::bitset<N> > {
    static const size_t size = N;
};
like image 38
Anycorn Avatar answered Dec 20 '22 06:12

Anycorn