foreach over enums?
Simen kjaeraas
simen.kjaras at gmail.com
Thu Sep 23 04:23:45 PDT 2010
%u <e at ee.com> wrote:
> The code didn't compile, so I tried fixing it.. and failed as I don't
> really get
> what you want it to do (or even how to call it :)
> Please explain it to me.
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 );
}
}
--
Simen
More information about the Digitalmars-d-learn
mailing list