Define bitset size at initialization?
Solution 1
Boost has a dynamic_bitset
you can use.
Alternatively, you can use a vector<bool>
, which (unfortunately) is specialized to act as a bitset. This causes a lot of confusion, and in general is considered a bad idea. But that's how it works, so if that's what you need, you might as well use it, I suppose.
Solution 2
Solution 3
You should check out boosts dynamic_bitset.
Solution 4
What you are saying at the beginning is not true. The "examples you found" did not look as you posted. It is impossible to use a non-constant value to parametrize a template. So, your first example is invalid. Only constant expressions can serve as non-type arguments for a template. I.e. the non-type argument has to be a compile-time constant.
Of looks like you want to create a bitset whose size is not a compile-time constant. In this case the bitset
template is out of question. You need an implementation of run-time sized bitset. For example, you can use std::vector<bool>
- in many (if not all) implementations this template is specialized to implement a packed array of boolean values, where each element occupies one bit (as opposed to an bool
object).
Martijn Courteaux
I'm writing Java, C/C++ and some Objective-C. I started programming in 2007 (when I was 11). Right now, I'm working on my magnum opus: an iOS, Android, OS X, Linux, Windows game to be released soon on all relevant stores. The game is written in C++ using SDL and OpenGL. A couple of seeds for my name (for java.util.Random, radix 26): 4611686047252874006 -9223372008029289706 -4611685989601901802 28825486102
Updated on January 05, 2020Comments
-
Martijn Courteaux over 4 years
I want to make a bitset in C++. I did a bit of research. All examples I found where like this:
bitset<6> myBitset; // do something with it
But I don't know the size of the bitset when I define the variable in my class:
#include <bitset> class Test { public: std::bitset *myBitset; }
This won't compile...
And initializing like this also doesn't work:
int size = getDependentSizeForBitset(); myBitset = new bitset<size>();