How to find out the size of a std :: bitset at compile time

Is there a way to find out the size std::bitset


I have

 typedef std::bitset<64> Bitset;


and I want to know the size without instantiating. For example. egBitset::size

When I look at sources in bitset.h

, it is completely unreadable to me, but even if I found these lines

    enum {_EEN_BITS = _Bits};   
    typedef _Bitset_base<_Bits <= 8 ? 1
        : _Bits <= 16 ? 2
        : _Bits <= 32 ? 4
        : 8> _Mybase;
    typedef typename    // sic
        _Mybase::_Ty _Ty;


which I thought told me it _Ty

could contain the size, but when I try to call Bitset::_Ty

I getillegal use of this type as an expression

I know I can store the size somewhere before I type the bitset, but that's not what I want.


source to share

4 answers

Use Bitset::digits

instead, which matches 64 in your case.

EDIT: As it turns out wrong, here's another solution:

template< typename T >
struct GetSize;

template< size_t Len > 
struct GetSize< std::bitset< Len > >
    enum { Length = Len };


Used for example:

const size_t bitsetLength = GetSize< std::bitset< 1024 > >::Length;




Since every C ++ Standard Library container std::bitset

has a size()

. In most cases, the usage is size()

fine because it will be included in the compiler.

There is no public member in C ++ 03 that you can use, for example, when parameterizing another template.

Since the method is size()

declared as constexpr

, you can use it to parameterize a template in C ++ 11 like this:

 std::bitset<34> b;
 std::bitset<b.size()> bx;


The standard still doesn't define any member std::bitset<N>

that you can use portable. There is a snippet in your question that defines enum {_EEN_BITS = _Bits};

so std::bitset<N>::_EEN_BITS

should be equal N

, but this is only available in Visual Studio.



Just use std::bitset<n>().size()

as Rafal Ravitsky says in his answer.

The compiler will optimize the temporary instance (compiled with -O2):

76:test.cpp      ****     int i = std::bitset<8>().size();
77:test.cpp      **** 
78:test.cpp      ****     std::cout << i << std::endl;
68                      .loc 1 78 0
69 0009 C7442404        movl    $8, 4(%esp) #,
69      08000000 
70 0011 C7042400        movl    $_ZSt4cout, (%esp)  #,
70      000000
71 0018 E8FCFFFF        call    _ZNSolsEi   #




Yes, template argument output works fine:

template<size_t N> char (&getBitsetSize(std::bitset<N>))[N];

Using: sizeof(getBitsetSize(Bitset());

C ++ 03, for C ++ 11 use Rafał Rawicki.



All Articles