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
View all comments
Show parent comment
19
u/ack_error Jul 19 '26
There are several reasons that bitfields are annoying where manual bit flags are generally used.
Bitfields have few guarantees with layout and so are unsuitable for interop, where specific bits must be set in integers of specific size. Plain integer arithmetic is far more universal than C or C++ bitfields.
The common ABIs have finicky rules regarding how types of bitfields affect layout. The type of each bitfield determines the integer that the bitfield is fit within, and in some cases this can require unnatural types to get the bitfields densely packed. https://gcc.godbolt.org/z/eK51eKraq
Should you want to check the bitfield layout at compile time, it requires C++20 for constexpr
bit_castand bitfields must fully and exactly cover the enclosing machine words so the struct is fully initialized... and currently it's not supported in Clang. https://gcc.godbolt.org/z/v8EYnafsnMember initializers for bitfield members also require C++20.
Bitfields can't be addressed or indexed. This means that patterns for quickly iterating over set bitfields or changing bitfields by a variable index can't be applied without bit-casting to and from integer.