Implicit enum conversions are a stupid PITA

Simen kjaeraas simen.kjaras at gmail.com
Sat Mar 27 07:02:53 PDT 2010


Andrei Alexandrescu <SeeWebsiteForEmail at erdani.org> wrote:

> alias Flags!(ubyte, "do_nothing",
>                      "walk_dog"
>                      "cook_breakfast"
>                      "deliver_newspaper"
>                      "visit_miss_kerbopple"
>                      "wash_covers") Todo;
>
> I encourage you to code that up and see how it swims. We need to stop  
> inventing syntax for any single thing that seems useful, and start  
> eating our dogfood. If our mechanism for code generation is not good  
> enough, we should improve it, not generate by hand ever new constructs.


template withType( alias F ) {
	template withType( alias s ) {
		enum withType = F!( typeof( s ) );
	}
}

mixin template Flags_mixin( T, U, U value, string name, V... ) {
	// Does not work, due to std.metastrings.toStringNow not supporting ubyte.
	//mixin( Format!( "enum %s = T( %s );", name, value ) );
	mixin( "enum " ~ name ~ " = T( " ~ to!string( value ) ~ " );" );
	static if ( V.length > 0 ) {
		mixin Flags_mixin!( T, U, value + 1, V );
	}
}

struct Flags( T = uint, U... ) if ( allSatisfy!( withType!( isSomeString
), U ) && isIntegral!( T ) ) {
	T value;
	mixin Flags_mixin!( typeof( this ), T, T.init, U );
}

usage:

void foo( ) {
	alias Flags!( ubyte, "a", "b", "c" ) myFlags;
	myFlags f = myFlags.a;
	writeln( f.value );

	alias Flags!( "d", "e", "f" ) myOtherFlags;
	myOtherFlags
}

It could do with some sanity checking (valid identifier names), but as
this was just a proof of concept, I have not written that.

btw, I really wish OpenGL headers could use a mechanism like this. Having
to look up every single function to see which flags are allowed can be a
PITA.

-- 
Simen



More information about the Digitalmars-d mailing list