using enums for flags

Jonathan M Davis jmdavisProg at gmx.com
Wed Jan 25 16:40:52 PST 2012


On Thursday, January 26, 2012 01:17:51 Trass3r wrote:
> > I think that it makes sense to use enums as flags, but I do _not_ think
> > that it makes sense to use an enum as the type of the variable _holding_
> > the flags.
> > 
> > STC var = STC.A & STC.B;
> 
> We could easily introduce @flags enum or whatever to make it more clear
> like in C#.
> 
> > just makes it worse. It should be something like
> > 
> > uint var = STC.A & FOO.F;
> 
> To me it doesn't make any sense at all to allow bitwise operations on
> different *named* enums.
> I also don't see why you would really need implicit conversion to the base
> type.
> 
> > For instance, std.socket uses flag enums, which is fine, but in some
> > places it uses them as the type of function parameters, which is _not_ a
> > good idea IMHO.
> 
> You really think int is any better??
> No type safety at all.

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


More information about the Digitalmars-d mailing list