I need a bitset with a slightly diffrent behavior when asigning variables with integer type to a specific bit. The bit should be set to zero if the assigned integer is smaller then one, and to one elsewise.
As a simple solution I copied the STL bitset, replaced the classname with altbitset, adjusted namespaces and include guard and added following function under reference& operator=(bool __x) in the nested reference class:
template <typename T>
reference& operator=(T i) {
if (i<1) return operator=(false);
return operator=(true);
}
It works as expected.
Question is if there is a better way doing this.
You shouldn’t copy a library just to add a new function. Not only that, the new function is wildly unintuitive and could possibly be the source of errors for even just reading the code, let alone writing it.
Before:
After:
Just write it out so it makes sense in your domain:
Remember: simplest doesn’t always mean fewest characters, it means clearest to read.
If you do want to extend the functionality of existing types, you should do so with free functions:
Giving:
But for such a small function with no clear “obvious” name that describes what it does concisely(
assign_bit_true_if_less_than_one_otherwise_falseis verbose, to say the least), just write out the code; it says the same thing anyway.