Originally Posted by
anon
I guess the red herring in the bits class (together with its name) is operator[]. This confuses the responsibilities of either class, and allows weirdness like:
Code:
twiddler x(8);
bool b = x[0][3]; //so, which bit do we want to access?
Good design would strive to make such nonsense a compile-time error (which would be achieved by not overloading [] in bits).
Another issue I have is with operator* in the twiddler class. Unary * means dereferencing and is there for classes that act like pointers (to dereference an iterator or a smart pointer).
So yeah, your friend does seem to have a tendency to misname functions/classes and cause confusion.
OTOH, the code works. This is how you can access bits with the array syntax.
Then what about this:
Code:
class twiddler;
class bit {
uint8_t& value;
int n;
friend class twiddler;
bit(uint8_t& value, int n) : value(value), n(n) {}
public:
bool operator*() { return (value & (1 << n)) != 0; }
bool operator=(bool set_value) {
if(set_value) {
value |= (1 << n);
} else {
value &= ~(1 << n);
}
}
};
class twiddler {
uint8_t value;
public:
twiddler(uint8_t value = 0) : value(value) {}
uint8_t& operator*() { return value; }
bit operator[](int n) { return bit(value, n); }
};
Which could be use like so:
Code:
twiddler t(8);
t[3] = false;
cout << *t[3] << end;