Lets look at very basic implementation of Bitset.
struct Bitset {
bool mask[32];
bool& operator[] (int index) {
return mask[index];
}
};
Now I can write
Bitset bitset;
bitset[0] = 1;
std::cout << bitset[0] << "\n";
There is possible optimization. I can use unsigned int instead of bool mask[32].
struct Bitset {
unsigned int mask;
bool& operator[] (int index) {
// ??
}
};
Is it possible to write bool& operator[] (int index) with such specification ? I think std::bitset is doing something like that but i have no idea how.
No, you can’t form a reference to anything smaller than
char.Instead, you could return an object that’s convertible to
bool, supports assignment, and knows which bit to read and write, along the lines of:As noted in the comments, you might also want some compound assignment operations to more fully emulate a reference. You might also want a separate type, containing a
constreference and no assignment operators, to return from aconstoverload ofoperator[].