How do I iterate over enum members at runtime?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Apr 9 15:37:34 PDT 2011


On 4/10/11, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
>> What the.. I was sure mixin wouldn't work in a foreach loop.
>
> Whyever not? mixins work in most places. I believe that the problem is that
> they have to be a whole expression or statement rather than just a piece of
> one, so sometimes you can't use a mixin for something small and have to put
> more of the code in a mixin, but string mixins do work in most places.
>
> - Jonathan M Davis
>

Well in this case it works, but it's not always so easy. For example:

import std.conv;
enum Metrics : int
{
    val0,
    val1,
    val2
}

void foo(int m)
{
}

void main()
{
   foreach (index; 0..3)
   {
       foo(mixin("Metrics.val" ~ to!string(index)));
   }
}

So even though you might think "hey, it's obvious index in this case
can never be anything other than 0, 1, or 2", you still won't be able
to compile this. CTFE is a tricky thing.


More information about the Digitalmars-d-learn mailing list