Static Foreach

nazo lovesyao at gmail.com
Tue Sep 19 03:22:52 PDT 2006


I have some suggestions.
How about support to "static foreach" as "static if"?
Problem is that it is not still able to use array in template arguments.

Example1:
import std.stdio;

int test(char[][] strs)(char[] a){
   switch(a){
     static foreach(const uint index,const char[] str;strs){
        case str:
          return index;
     }
   }
   return -1;
}

int main(char[][] args){
   if(args.length<2)return -1;
   writefln(test!([cast(char[])"test","test2","test3"])(args[0]));
   return 0;
}

Example2:
//if dmd supported "identifier"(See Template-based Processing Thread)
import std.stdio;

template T(char[][] a){
   interface Base(){
     void print();
     Base next();
   }
   static foreach(const int index,const char[] b;a){
     class identifier(b):Base{
       void print(){
         writefln(b);
       }
       Base next(){
         return new identifier(a[index+1%a.length]);
       }
     }
   }
}

mixin T!([cast(char[])"Test","Test2","Test3"]);

int main(){
   Base a=new Test;
   for(int i;i<10;i++){
     a.print;
     a=a.next();
   }
   return 0;
}

**Following is an addition**

-compile Attribute
there is no variable for compile time only.(const is merely constant)

Example:
old:
template T(int a){
   const int i=a;
   const int i2=i*i;
   const int i3=i2*i2;
   const int i4=i3*i3;
   const int i5=i4*i4;
   const int T=i5;
}
auto i=T!(10).T;

new:
template T(int a){
   compile int i=a;
   i*=i;
   i*=i;
   i*=i;
   i*=i;
   const int T=i;
}
auto i=T!(10);

-static for
template T(int a){
   compile int i=a;
   static for(compile int i2=0;i2<4;i2++){
     i*=i;
   }
   const int T=i;
}
auto i=T!(10);

-- 
Nazo

I want that D should be more chaosful!



More information about the Digitalmars-d mailing list