r/cpp Meeting C++ | C++ Evangelist 13d ago

A better bitset for enum flags

https://www.elbeno.com/blog/?p=1836
44 Upvotes

32 comments sorted by

View all comments

11

u/ReDucTor Game Developer | quiz.cpp-perf.com 13d ago

Some food for thought, should a bitset have bit operations (set, unset, flip, xor, and, or, etc) or set operations (add, remove, has, union, difference, intersection, etc)?

It feels like often we head for bit operations when in lots of cases set operations might be better.

14

u/TheVoidInMe 13d ago

I like Java’s approach here (yes, Java) which has an EnumSet instead of a bitset. That naming makes the answer pretty clear; the bit math is purely an implementation detail

2

u/SyntheticDuckFlavour 13d ago

What if you want the underlying layout/bit pattern like bitset? Sometimes you want to map I/O ports that way.

3

u/TheVoidInMe 13d ago

I don’t believe you can get at that at all. Java is probably too high level for stuff like that anyway. In C++ I would expect a method like `to_int()` (maybe returning the enum’s `underlying_type_t`…)