foreach over string enum

Daniel Murphy yebblies at nospamgmail.com
Sun Feb 20 17:43:10 PST 2011


"Jesse Phillips" <jessekphillips+D at gmail.com> wrote in message 
news:ij2drt$1mq3$1 at digitalmars.com...
>
> Magic.
>
> No really, the best I can tell is that the compiler will try to run the 
> foreach loop at compile-time if there is something in the body that must 
> be evaluated at compile time.
>

Actually this happens because __traits(allMembers ...) returns a TypeTuple 
of string literals.
TypeTuples can contain elements of different types (and types themselves as 
elements), so in order for them to be used in foreach loops, they MUST be 
unrolled.

It's not something in the body, it's the iterable itself that forces 
unrolling.

http://www.digitalmars.com/d/2.0/tuple.html

You can do LOTS of cool stuff with this:

switch(x)
{
  foreach(i; TypeTuple!(1, 2, 6, 8, 17))
    case i:
  doSomething();
}

---------------

class C {}
class D : C {}
class E : C {}
class F : C {}
class G : C {}

C[] list;
foreach(T; TypeTuple!(D, E, F, G))
  list ~= new T();

----------------

int id = runtimeInput();

foreach(i, T; TypeTuple!(C, D ,E, F, G, H))
  if (i == id)
    return new T(); 




More information about the Digitalmars-d-learn mailing list