Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

enum with flags, overloaded operators and switch

42 views
Skip to first unread message

Marcel Mueller

unread,
Jun 26, 2016, 10:33:44 AM6/26/16
to
When I use enums with flags an define the type safe bit operators I get
warning in switch statements when I have bit combinations in a case
constant. (case value not in enumerated type)

Basically the overloaded operators cause the argument to switch to be of
the enum type rather than int. And now the compiler (here gcc) does some
consistency checks.
It is just a warning and I can turn it off, but this disables another
sometimes useful warning for other enum types that not all enum values
of the switch are handled.

Is there anything else I can do except for casting to int at the switch
statement?


enum Flags
{ None = 0
, Val1 = 1
, Val2 = 2
//...
};

inline constexpr Flags operator|(Flags l, Flags r)
{ return (Flags)((int)l|r); }
// further operators

int main()
{
Flags f = Val1|Val2;
switch (f)
{default:
return 0;
case Val1:
return 1;
case Val2:
return 2;
case Val1|Val2: // Warning!
return 3;
}
}

Alf P. Steinbach

unread,
Jun 26, 2016, 11:21:39 AM6/26/16
to
On 26.06.2016 16:31, Marcel Mueller wrote:
> When I use enums with flags an define the type safe bit operators I get
> warning in switch statements when I have bit combinations in a case
> constant. (case value not in enumerated type)
>
[snip]
switch (+f)
{default:
return 0;
case Val1:
return 1;
case Val2:
return 2;
case Val1|Val2: // Warning!
return 3;
}
}


Cheers & hth.,

- Alf

Marcel Mueller

unread,
Jun 27, 2016, 3:25:55 PM6/27/16
to
On 26.06.16 17.19, Alf P. Steinbach wrote:
> switch (+f)

At least it looks more pretty.


Marcel
0 new messages