I have written a templates class for storing multiple bools in an integer.
Right now, setting and getting each bool is done with explicit functions
bool isBitSet(int index)
{
return static_cast<bool>((block_ >> index) % 2)
}
void setBitOn(int index)
{
block_ |= 1 << index;
}
I believe that the following would work for getting a value, but how would setting work since we can’t directly return a reference for a bit?
const bool operator [] (int index) const
{
return static_cast<bool>((block_ >> index) % 2);
}
The same is done in
std::vector<bool>and instd::bitsetin the standard library. As stated in the reference,std::vector<bool>it returns a proxy class that has its operators overloaded to act as an element of the vector.You could to that as well.
For a user-friendly example see again the reference for a public interface, it is something like this:
To implement this class you should store a member pointer to your actual data block and a mask to operate with.
For a real example, in the g++ headers look for member class of
std::vector<bool>calledstd::vector<bool>::_Bit_referencein the filebits/stl_bvector.h.To clarify the OP with an example:
Let’s say you have a class containing 320 bools. You could write it as:
You want to add an operator[]. To add a const one is easy:
to have a non-const one you need much more. First you need to create a class that represents a reference to your value. You must have some kind of pointer to where the value is stored and (in this case) you need a bitmask to specify one concrete bit. To be able to handle this as a bool& you need to add some operators, namely conversion to bool and operator=:
Note that the above struct will behave as a bool& — reading from it reads the value from the data point represented by the pointer and the mask, and similarly, writing to it overwrites the bit at the represented location. I also wrote a constructor that initializes the members.
Now all you need is that your boolcontainer’s operator[] should return an object of the above class:
And now some code to test it (prints only the first 40 values):