foreach over enums?

%u e at ee.com
Wed Sep 22 18:31:54 PDT 2010


== Quote from Simen kjaeraas (simen.kjaras at gmail.com)'s article
> %u <e at ee.com> wrote:
> > == Quote from Simen kjaeraas (simen.kjaras at gmail.com)'s article
> >> %u <e at ee.com> wrote:
> >> > enum X { A=3, B=1, C }
> >> >
> >> > void main() {
> >> >     foreach(e;X)
> >> >         writefln(e.stringof," = ",e);
> >> > }
> >> > //X.A = 3
> >> > //X.B = 1
> >> > //X.C = 2
> >> > or
> >> > //X.B = 1
> >> > //X.C = 2
> >> > //X.A = 3
> >> enum X { A=3, B=1, C }
> >> void main( ) {
> >>      foreach( e;  __traits(allMembers, X) ) {
> >>          writeln( "X.", e, " = ", mixin( "X."~e ) );
> >>      }
> >> }
> >
> > D1 :'(
> Oh. Without being an expert on D1 matters, I believe that is impossible.
> I thought there was a struct called defineEnum in phobos1, but it
> appears I am wrong. However, it should be fairly simple to create one.
> Untested code, as I do not have D1 installed:
> struct defineEnum( T... ) {
>      foreach ( i, e; T ) {
>          mixin( "static defineEnum " ~ e ~ " = defineEnum( i );" );
>      }
I think in D1, the foreach need to be encapsulated in a char[] function().


>      static int opApply( int delegate( ref bar ) dg ) {
>          int result = 0;
>          foreach ( e; T ) {
>              mixin( "result = dg( " ~ e ~ " ) );" );
Why is this a mixin?

>              if ( result ) {
>                  break;
>              }
>          }
>          return result;
>      }
> }
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.



More information about the Digitalmars-d-learn mailing list