How do I iterate over enum members at runtime?

Jesse Phillips jessekphillips+d at gmail.com
Sat Apr 9 13:44:19 PDT 2011


On Sat, 09 Apr 2011 16:20:06 -0400, Andrej Mitrovic wrote:

> I know there's traits to get strings at compile time, e.g.: auto b = [
> __traits(allMembers, Metrics) ];
> 
> but this doesn't help me try out those enum values at runtime. It could
> almost work if I could use a mixin() in a foreach loop, but that's lucid
> dreaming.
> 
> Another alternative might be to create an array out of the enum, but I
> don't know of any way of doing this.

You have everything you need, just put them all together:

enum Metrics : int
{
	SM_CXSCREEN = 0,
	SM_CYSCREEN,
	SM_CXVSCROLL,
	SM_CYHSCROLL,
	SM_CYCAPTION,
	SM_CXBORDER,
}

void foo(int m)
{
}

void main()
{
    foreach (m; __traits(allMembers, Metrics))
    {
        foo(mixin("Metrics." ~ m));
    }
}



More information about the Digitalmars-d-learn mailing list