This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH] Type-safe wrapper for enum flags


On 10/29/2015 06:45 PM, Pedro Alves wrote:
> 
>   enum foo_flags flags = 0;
> 
>   if (...)
>     flags |= FOO_FLAG1;
>   if (...)
>     flags |= FOO_FLAG2;
> 
> ... would have to be written as:
> 
>   enum foo_flags flags = (enum foo_flags) 0;
> 
>   if (...)
>     flags = (enum foo_flags) (flags | FOO_FLAG1);
>   if (...)
>     flags = (enum foo_flags) (flags | FOO_FLAG2);
> 
> which is ... ugly.  Alternatively, we'd have to use an int for the
> variable's type, which isn't ideal either.

... for losing type safeness.  Looks like I forgot to mention
the "type-safe" part.  This thus also avoids mistakes like:

 enum foo { foo_val1, foo_val2 };
 enum bar { bar_val1, bar_val2 };

 enum foo f = 0;

 f |= bar_val2;

While the above compiles in C, the below doesn't, in C++:

 enum foo_values { foo_val1, foo_val2 };
 enum bar_values { bar_val1, bar_val2 };
 DEF_ENUM_FLAGS_TYPE (enum foo_values, foo);
 DEF_ENUM_FLAGS_TYPE (enum bar_values, bar);

 foo f = 0;

 f |= bar_val1;

with:

$ g++ ...
foo.c:30:5: error: no match for âoperator|=â (operand types are âfoo {aka enum_flags<foo_values>}â and âbar_valuesâ)
   f |= bar_val1;
     ^

Thanks,
Pedro Alves


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]