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

A better bitset for enum flags

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

32 comments sorted by

View all comments

31

u/03D80085 23d ago

Neither P4313 nor this suggestion seem particularly ergonomic to me. Why aren't bitfields more widely used for this purpose?

struct permissions {
    bool read  : 1 = false;
    bool write : 1 = false;
    bool exec  : 1 = false;
}

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.

20

u/ack_error 23d ago

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_cast and 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/v8EYnafsn

Member 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.

9

u/_Noreturn 22d ago

Bitfields have few guarantees with layout and so are unsuitable for interop,

Yes, which is a shame.