Le mardi 17 mars 2026 à 05:25 +0100, Rainer Deyke via Boost a écrit :
On 3/16/26 11:59, Tobias Loew via Boost wrote:
While better support for bit flags based on scoped enums is undoubtedly useful, I don't like how verbose the example code is.
I've considered an alternate solution to the same problem based on a wrapper around std::bitset.
template<typename Enum> class enum_bitset { public: auto operator[](Enum idx) { return this->data_store[static_cast<std::size_t>(idx)]; } // ...and all of the other member functions... private: std::bitset<...> data_store; };
This has the advantage of getting rid of all of the ugly boost::flags::nth_bits and boost::flags::anys in the example code:
enum class pizza_topping { tomato, cheese, salami, olives, garlic };
void order_pizza(enum_bitset<pizza_topping> const &toppings) { std::cout << "Pizza ordered with\n"; if (toppings[pizza_toppings::tomato]) { std::cout << "- tomato\n"; } if (toppings[pizza_toppings::cheese]) { std::cout << "- cheese\n"; } if (toppings[pizza_toppings::salami]) { std::cout << "- salami\n"; } if (toppings[pizza_toppings::olives]) { std::cout << "- olives\n"; } if (toppings[pizza_toppings::garlic]) { std::cout << "- garlic\n"; } std::cout << "\n"; }
Isn't that so much more readable and compact?
Much more. This is one of the reason i included bitset support in my indexed_array library ( https://github.com/Julien-Blanc-tgcm/indexed_array ), the bitset doing exactly that : access individual bits via an enum value. I've come to the conclusion that any representation of enum flags with C++ enums is a design mistake by itself (a pretty widespread one, but still a mistake). Enums are individual values, enum flags are a set of values, they are different by nature. In C++, different things deserve a different type, call it an enum_bitset, an enum_set or whatever, but donc make it a plain enum / enum class. Regards, Julien