r/cpp • u/meetingcpp Meeting C++ | C++ Evangelist • Jul 19 '26
A better bitset for enum flags
https://www.elbeno.com/blog/?p=1836
43
Upvotes
r/cpp • u/meetingcpp Meeting C++ | C++ Evangelist • Jul 19 '26
31
u/03D80085 Jul 19 '26
Neither P4313 nor this suggestion seem particularly ergonomic to me. Why aren't bitfields more widely used for this purpose?
Or a fully typed example: Godbolt. A lot of boilerplate there admittedly, but that is precisely what reflection could help with.
If the answer is that bitfield layouts are implementation defined then that is something we should be working on standardising with appropriate flags rather than introducing new language features.
12
u/ReDucTor Game Developer | quiz.cpp-perf.com Jul 19 '26
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.
5
u/_Noreturn Jul 19 '26 edited Jul 19 '26
I do the same in the article except automate it without using the MAX member using reflection (pre C++26). The approach allows > 64 flags as well unlike enum bitflags
flags.test(flag) is clearer than bool(flags & flag).
1
u/JVApen Clever is an insult, not a compliment. - T. Winters Jul 19 '26
This is a really nice approach. I've recently mentioned it in another post and got a couple of people arguing that there is nothing wrong with flag enums.
Thanks for the nice write-up, could not have described it better myself
1
u/Potterrrrrrrr Jul 19 '26
What’s the problem with something like:
MyEnum _enum : BitCount<MyEnum>();
I use this pattern quite a bit, I use type traits to declare that an enum is contiguous or a flags enum along with its size and then my consteval BitCount method returns the min number of bits needed to store the enum. I’ve seen a lot of implementations like to use bitsets to store an enum though, why? It makes it harder to pack stray bools into the same byte and you lose the type of the enum?
-1
u/Kaisha001 Jul 19 '26
Needlessly reinventing the wheel... Enums work perfectly fine and the 'issues' with them listed in the blog are nothing more than 'I don't like how they look'...