strong enums: why implicit conversion to basetype?

Era Scarecrow rtcvb32 at yahoo.com
Fri Jan 27 11:01:58 PST 2012


> >> El 26/01/2012 14:59, Trass3r escribi?:
> >>> I thought it'd be good to outsource this
> question from the other thread
> >>> about enums as flags.
> >>>
> >>> Is there any merit in having implicit
> conversion to the basetype?
> >>> Imo it only introduces a severe bug source and
> brings no advantages.
> >>
> > Sometimes, bitwise operations make sense, other times
> not. Enums play two
> > roles in D - that of an enumeration and that of a set
> of flags. Only for
> > the latter do bitwise operations make sense.
> 
> You'd think that with some use of a templated struct and
> some "alias 
> this" we'd be able to have a strongly-typed type for storing
> sets of 
> flags.  It could even offer convenience functions like
> "getFlag" and 
> "setFlag" to make the code read a bit nicer.

 I have a personal class i am using, may submit it later to Walter to add to Phobos. Comments? (I have working unittests... :) )


///T of type ENUM, and S of an integral.
struct HandleFlags(T, S)
 {
	S state;	///Holds state.
	alias T T_Enum;

	 this(T[] setFlags...);

	///Returns true/false if a specific ENUM flag has been set.
	bool check(T[] flag...);

	///Returns true/false if a specific ENUM flag has been set.
	bool checkAll(T[] flag...);
	
	/**
	Checks if a flag has been set, returning that ENUM, otherwise returning the Else flag.
	*/
	T checkElse(T Else, T[] flag...);

	///Sets specific flag(s) on
	void setFlag(T[] flag...);

	///turns listed flags off.
	void clearFlag(T[] flag...);

	///reverses the state of a specific flag.
	void flipFlag(T[] flag...);
}



More information about the Digitalmars-d mailing list