www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: using enums for flags

 On Wed, 25 Jan 2012 03:22:03 +0100, Trass3r <un known.com>
 wrote:
 Does it really make sense to allow bitwise operations

=20 Maybe. Certainly sometimes, but those could just as easily use casts. =20
 There should at least be some way to get this straight

 resort to a heap of code like in C++:=A0=20


To my understanding, converting an int to an enum (In C++ or D) is basical= ly illegal. You'd have to do force casting to get it to work, which isn't s= afe. Enums seem better suited for a long range of codes that don't have spe= cific bits for on/off If it hasn't been suggested yet, I am currently using a block of personal = code to use enums as flags. I'll give you a stripped down version of the st= ructure, if everyone says 'yay' or perhaps Walter feels he wants it, we can= propose maybe get it in phobos. How it works, is internally it will store the flag as an int (or whatever = type S is), then you can do checks and it will convert the enum to an int a= nd do appropriate bit casts. Haven't tried to consider how to get a array o= f separate flags. ///T of type ENUM, and S of an integral. struct HandleFlags(T, S) { =09S state;=09///Holds state. =09alias T T_Enum; =09this(T[] setFlags...); =09///Returns true/false if a specific ENUM flag has been set. =09bool check(T flag); =09/** =09Checks if a flag has been set, returning that ENUM, otherwise returning = the Else flag. =09*/ =09T checkElse(T flag, T Else); =09 =09///Sets specific flag on or off. Default sets flag =09void setFlag(T flag, bool on_off =3D true); =09 =09///reverses the state of a specific flag. =09void flipFlag(T flag); } Usage is like this. =09enum ETEST {zero =3D 0, one =3D 1, two =3D 2, four =3D 4} =09HandleFlags!(ETEST, int) ftest; =09HandleFlags!(ETEST, int) ftest1(ETEST.one); //1 =09HandleFlags!(ETEST, int) ftest2(ETEST.two, ETEST.four); //6
Jan 25 2012