CT foreaches

Timon Gehr timon.gehr at gmx.ch
Fri Aug 1 22:08:47 UTC 2025


On 8/1/25 15:51, monkyyy wrote:
> ```d
> import std;
> void foo(int i:0)()=>"foo".writeln;
> void foo(int i:1)()=>"bar".writeln;
> void foo(int i:2)()=>"foobar".writeln;
> void main(){
>      foreach(i,alias b; AliasSeq!("foo","bar")){
>          pragma(msg, b.stringof);
>              break;
>      }
>      pragma(msg,"---");
>      foreach(i,enum b; AliasSeq!("foo","bar")){
>          pragma(msg, b.stringof);
>          break;
>      }


These behave like lined out in Proposal 1 of DIP 1010.

Code snippets from the DIP:

```d
foreach (enum v; AliasSeq!(x,y,z)) { ... }
```

```d
foreach (alias v; AliasSeq!(x,y,z)) { }
```

https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1010.md#proposal-1-allow-enum-and-alias-variables-for-unrolled-foreach-statements

>      pragma(msg,"---");
>      static foreach(i;0..3){
>          pragma(msg, i.stringof);
>          //break; //the scope error
>      }
>      pragma(msg,"---");

This is just a standard `static foreach`.

>      foreach(enum i;0..3){// ERROR ISNT CT. ISNT AN ENUM
>          pragma(msg, i.stringof);
>          //foo!i; //doesnt compile
>          break;
>      }
> }
> ```
> ...

This one is a bug, quote from DIP1010:

 > Currently, it is an error to use alias or enum on a regular foreach loop:
 >
 > ```d
 > foreach (enum i; 0 .. 3){ ... } // error
 > ```
 >
 > It has been suggested that this should instead unroll the loop, such 
that it becomes equivalent to:
 >
 > ```d
 > foreach (enum i; AliasSeq!(0,1,2)) { ... }
 > ```

https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1010.md#allowing-alias-and-enum-on-regular-foreach-loop-variables

https://github.com/dlang/dmd/issues/21630
https://github.com/dlang/dmd/pull/21631


More information about the Digitalmars-d mailing list