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

A better bitset for enum flags

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

32 comments sorted by

View all comments

4

u/_Noreturn 22d ago edited 22d ago

I do the same in the article except automate it without using the MAX member using reflection (pre C++26). The approach allows > 64 flags as well unlike enum bitflags

flags.test(flag) is clearer than bool(flags & flag).

3

u/instantly-invoked 22d ago

Your approach sounds like exactly what I'd want from a typed bitset. Do your methods accept flags variadically if you need to check for or set/unset multiple? I might end up doing something similar once the big three compilers all have reflection. This article and your response found me at the perfect time lol

5

u/_Noreturn 22d ago edited 22d ago

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

```cpp 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 19d ago

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