简体   繁体   中英

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.

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 .

Bitset could have been a class rather than a template.

It is made for a purpose and if that is not yours, you simply have to use something different.

If you want to store single bits, which means you like to store bool with variable size, you simply can use std::vector< bool >

If not, I'll have to use std::vector and implement bitset members myself.

A bitset is a container of bits. So what do you mean by implementing bitset yourself?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM