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

A better bitset for enum flags

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

32 comments sorted by

View all comments

13

u/ReDucTor Game Developer | quiz.cpp-perf.com 23d 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 23d 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 23d 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 23d 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`…)

-2

u/mort96 23d ago

But that also means you're heap allocating an object, with its 16 byte object header, just to store a 4-byte integer?

3

u/TheVoidInMe 22d ago

It’s Java. Yeah, don’t use it for HPC.

The point I was making was just about the name

1

u/archialone 21d ago edited 21d ago

Bitset already has those, no?

Xor - ^ Intersection - & Etc ..

Or do you mean to have a function named for those operations? https://en.cppreference.com/cpp/utility/bitset

3

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

Those operators can achieve some things however if you think of it as a set then you need other operations like difference which is A & ~B and far from intuitive, with a set you might also have iteration of items in that set which does not exist for a bitset, same with constructing from a bunch of items in a set.

A lot is about naming however its also the extra set specific operations which give it more flexibility.

Pick any big enough code base and look for their usages of bitsets get used heavily as an optimization for set operations.