Search code examples
c++templatesstdbitsetvariable-length-array

Why does std::bitset only takes constexpr value?


I want to decide size of bitset during runtime.
But std::bitset<N> only accepts constexpr values for N, not even const values.
Which means size of bitset must be decided before compiling.

I know std::vector provides optimization for bool array,
but it lacks those useful bitset members I need.

Question 1: Why does N has to be constexpr value?
Well I'm guessing that's because bitset is template, but still, this is massive inconvenience.
Bitset could have been a class rather than a template.
It's constructor can take size_t as argument, than I can create variable length bitset.
The same question goes for std::array.
Could've been std::array<type> foo(size, values).

Question 2: Is there any 'Hacks' that lets me create variable-length bitset?
I'm pretty sure there won't be any, considering how template works.
But just maybe, there is some clever trick :)
If not, I'll have to use std::vector<bool> and implement bitset members myself.


Solution

  • Why does N has to be constexpr value?

    You are right. Size of both std::bitset and std::array is specified as a template parameter, so it cannot be set during runtime.

    However, in the past there were some proposals for introducing dynamic arrays in the C++ standard. One of them was called std::dynarray. Eventually, it won't be introduced into standard but you can see here a more elaborative description of its lifetime.

    Is there any 'Hacks' that lets me create variable-length bitset?

    If you have access to the Boost library, you can use its dynamic_bitset.