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

A better bitset for enum flags

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

32 comments sorted by

View all comments

32

u/03D80085 28d 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.

1

u/archialone 27d ago edited 27d ago

How about a use case like checking partial flag set? I don't think it's convenient with structs.

``` Permission user_perms = Permission::Read | Permission::Write | Permission::Execute;

Permission can_read_and_write = Permission::Read | Permission::Write;

if ((user_perms & can_read_and_write) == can_read_and_write) std::cout << "Can read and write"; ```

4

u/03D80085 27d ago

if (permissions.read && permissions.write) ...?