using enums for flags

Mantis mail.mantis.88 at gmail.com
Wed Jan 25 17:43:55 PST 2012


26.01.2012 2:40, Jonathan M Davis пишет:
> What type safety? You're dealing with a uint (or ushort or ulong) with a bunch
> of specific bits set which represent flags. What other type would you want? You
> could typedef it I suppose (well, use the TypeDef library type when it's
> merged in anyway), but you're dealing with a fixed number of bits, which is
> exactly what an unsigned integer is. It's just a question of which are on and
> which are off. That's certainly not what _enum_ is for. It's a fixed set of
> values.
>
> And that's my beef with using it as the result of&ing flags. The result isn't
> one of those flags, so it has no business being an enum.
>
> -  Jonathan M Davis
>
I agree, enum variable should only contain one of the enumerated values. 
Here's an example how current way may lead to unexpected result:

enum Foo { A = 1, B }

void bar( Foo foo ) {
     final switch( foo ) {
         case Foo.A:
             writeln( "A" );
             return;
         case Foo.B:
             writeln( "B" );
             return;
     }
     writeln( "Unreachable branch" );
}

int main() {
     bar( Foo.A | Foo.B );
     return 0;
}

It is intuitive to assume that the final switch will always hit one of 
it's branches, yet this doesn't work here.


More information about the Digitalmars-d mailing list