Fun with allMembers

Denis Koroskin 2korden at
Thu May 14 11:50:07 PDT 2009

On Thu, 14 May 2009 07:22:54 +0400, Shin Fujishiro <rsinfu at> wrote:

> Hi,
> I've had fun with the allMembers traits over the past few days and found
> it more powerful than I thought.
> __traits(allMembers, T) returns the member names of T. As some might
> already know, T is not restricted to a class or struct; it can also be
> an enum, template, or even module. Try this:
> --------------------
> enum E { a, b, c }
> template T() { int x, y, z; }
> import std.stdio;
> pragma(msg, __traits(allMembers, E).stringof);
> pragma(msg, __traits(allMembers, T).stringof);
> pragma(msg, __traits(allMembers, std.stdio).stringof);
> --------------------
> You'll like the result :). It must be usable!
> For example, using allMembers with enums, I could implement
> enumToString and enumFromString without defineEnum.
> Code:
> So, what other uses could there be?

Great, now the following is possible with your code:

string toString(Enum)(Enum e) if (is(Enum == enum))
    return enumToString(e);

assert("RED" == toString(c));

// and, once implemented:
assert("RED" == c.toString());

Although returning "Color.RED" might be better, but it's really not a problem.
Is there any way your code could be contributed to Phobos?

More information about the Digitalmars-d mailing list