Use members of a Named Enum without using Enum name?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 15 15:06:01 PDT 2015


On 08/15/2015 09:22 AM, QuizzicalFella wrote:
> On Saturday, 15 August 2015 at 15:53:23 UTC, Adam D. Ruppe wrote:
>> On Saturday, 15 August 2015 at 15:37:42 UTC, QuizzicalFella wrote:
>>> I'd like to be able to call someFunc(TRIANGLE) rather than
>>> someFunc(PolygonT.TRIANGLE).
>>
>> Two options come to mind:
>>
>> alias TRIANGLE = PolygonT.TRIANGLE;
>> // etc
>>
> ...if I wanted to write a mixin that iterated over all the elements in
> an enum, how would I get a member to print its name without the type?
> And how do I get the type to print itself?
>
> foreach(member; enum)
>      char[] output ~= "alias
> "~member.name~"="~enum.name~"."~member.name~";"
>
>

Fundamentally, __traits(allMembers) and .stringof but the following 
enumMembers present them as a range:

import std.stdio;

enum PolygonT : byte { TRIANGLE, RECTANGLE, STAR }

auto enumMembers(E)()
{
     import std.conv : to;
     import std.algorithm : map;

     return [ __traits(allMembers, E) ].map!(a => a.to!string);
}

void info(E)()
{
     writefln("The members of %s: %-(%s, %)",
              E.stringof, enumMembers!PolygonT);
}

void main()
{
     info!PolygonT();
}

Ali



More information about the Digitalmars-d-learn mailing list