This is the mail archive of the
gdb-patches@sourceware.org
mailing list for the GDB project.
Re: [PATCH] Type-safe wrapper for enum flags
- From: Pedro Alves <palves at redhat dot com>
- To: gdb-patches at sourceware dot org
- Date: Thu, 29 Oct 2015 19:00:57 +0000
- Subject: Re: [PATCH] Type-safe wrapper for enum flags
- Authentication-results: sourceware.org; auth=none
- References: <1446144341-21267-1-git-send-email-palves at redhat dot com>
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