foreach over enums?

%u e at ee.com
Thu Sep 23 15:56:39 PDT 2010


== Quote from Simen kjaeraas (simen.kjaras at gmail.com)'s article
> Sorry, it was late and I was tired. Updated code (tested, even! :p):
> module foo;
> import std.stdio;
> template defineStaticImpl( T, int value, string name, args... ) {
> 	mixin( "static T " ~ name ~ " = cast(T)value; " );
> 	static if ( args.length != 0 ) {
> 		mixin defineStaticImpl!( T, value + 1, args );
> 	}
> }
> template defineStatic( T, args... ) {
> 	mixin defineStaticImpl!( T, 0, args );
> }
> struct defineEnum( T... ) {
> 	int value;
> 	static const int num = T.length;
> 	mixin defineStatic!( typeof( this ), T );
>      static int opApply( int delegate( ref defineEnum ) dg ) {
>          int result = 0;
>          foreach ( i, e; T ) {
>              result = dg( defineEnum( i ) );
>              if ( result ) {
>                  break;
>              }
>          }
>          return result;
>      }
> 	static defineEnum opCall( int value ) {
> 		defineEnum tmp;
> 		tmp.value = value;
> 		return tmp;
> 	}
> 	string toString( ) {
> 		foreach ( i, e; T ) {
> 			if ( i == value ) {
> 				return e.dup;
> 			}
> 		}
> 	}
> }
> void main( ) {
> 	alias defineEnum!( "A", "B", "C" ) Bar;
> 	foreach ( e; Bar ) {
> 		writefln( e );
> 	}
> }
Okee, that took me a while to wholly get. :)

First question, shouldn't the first foreach be replaced by a simple for loop:
for(int i = 0; i<num; i++ ) {

If I understand it correctly the foreach aggregates are actually string-tuple
literals.
Then couldn't the second one be CT translated to char[][]?
That way the stringOf would be a simple array index.

And lastly, I probably need to make the whole struct a string mixin if I want it's
type to be like an enum.. don't I? :'(


More information about the Digitalmars-d-learn mailing list