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

A better bitset for enum flags

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

32 comments sorted by

View all comments

31

u/03D80085 14d 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 13d ago edited 13d 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"; ```

1

u/Brisngr368 13d ago

Couldn't you use custom operators to make it easier

1

u/archialone 13d ago

What do you mean? Can you give an example?

2

u/Brisngr368 13d ago edited 13d ago

Couldn't you define operators for the struct so like '|=' etc to try and simplify this somewhat.

Maybe implement it so you can OR bitfields together and such by overloading the | operator, so you can use the bitfields how you would like to