r/cpp • Meeting C++ | C++ Evangelist • Jul 19 '26

A better bitset for enum flags

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

32 comments sorted by

View all comments

Show parent comment

5

u/_Noreturn Jul 19 '26 edited Jul 19 '26

I might end up doing something similar once the big three compilers all have reflection

you could use c++17 reflection libraries like magic_enum or enchantum they both provide a bitset type and an array type. so you don't have to wait for c++26

Do your methods accept flags variadically if you need to check for or set/unset multiple

No but that's a nice idea i just use multiple expressions.

It is just a stupid wrapper like this

enum class Flag {
 Flag1,
 Flag2,
 Flag3,
 Flag4 = 7, // doesn't have to be contiguous 
 Flag5,
 Flag6,
 Flag7,
}
bitset<Flag> f({Flag::Flag1,Flag::Flag2}); // has size 7
f.set(Flag::Flag4);
f.reset(Flag::Flag4);
f.test(Flag::Flag5);
f.flip(Flag::Flag7);
f[Flag::Flag6] = false;

f.to_string(); // "Flag1 | Flag2 | Flag7"

2

u/xiao_sa Jul 22 '26

I kinda start to like this more than raw enum as bit flags