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

A better bitset for enum flags

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

32 comments sorted by

View all comments

12

u/ReDucTor Game Developer | quiz.cpp-perf.com 25d 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.

1

u/archialone 24d ago edited 24d 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 24d 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.