
Le lun. 29 oct. 2018 à 00:01, Arvid Norberg <arvid.norberg@gmail.com> a écrit :
On Thu, Oct 25, 2018 at 11:28 PM Masse Nicolas via Boost < boost@lists.boost.org> wrote:
Hi all,
[...]
enum struct option : uint { none = 0, first = 1, second = 2, third = 4, forth = 8 };
static constexpr flags<option> var1 = option::first; static constexpr flags<option> var2 = option::second | option::third; static constexpr auto var3 = var1 | var2; /* type will be resolved into flags<option> */ static constexpr auto var4 = option::first | option::second | option::third; /* works too */
I think a better approach is to fully define the flag type as a class (without the enum). It gives you slightly less typing for the user. Such flags type would be defined similar to how the NamedType library is used. There's also a neat trick to not have to manually specify powers of two (and possibly get it wrong) using a separate type for bit numbers.
using my_flags_type = flag_type<std::uint8, struct my_flags_tag>; constexpr my_flags_type red = 0_bit; constexpr my_flags_type green = 1_bit; constexpr my_flags_type blue = 2_bit;
I describe such a flag type in this lightning talk: https://www.youtube.com/watch?v=NGrnKr9rSz4
-- Arvid Norberg
Hi, I had a quick look at your presentation. While I do think that using a class is an option, I still prefer to use enums for that, for several reasons: - The use of an enum for the values makes a clear differences betwen them and the flags (which are a combinaison of those values). - The use of enums allows to scope the values inside their name, while using your solution makes them visible directly inside your namespace. - The need of a tag struct is be a bit odd, espescially for now comers Anyway, I should say I like the idea of having an helper class to avoid the specification of to power of two. As a consequence, I will probably add something similar in my code. Nicolas.