EnumMembers

Retrieves the members of an enumerated type enum E.

template EnumMembers (
E
) if (
is(E == enum)
) {}

Parameters

E

An enumerated type. E may have duplicated values.

Return Value

Static tuple composed of the members of the enumerated type E. The members are arranged in the same order as declared in E. The name of the enum can be found by querying the compiler for the name of the identifier, i.e. __traits(identifier, EnumMembers!MyEnum[i]). For enumerations with unique values, std.conv.to can also be used.

Note: An enum can have multiple members which have the same value. If you want to use EnumMembers to e.g. generate switch cases at compile-time, you should use the std.meta.NoDuplicates template to avoid generating duplicate switch cases.

Note: Returned values are strictly typed with E. Thus, the following code does not work without the explicit cast:

enum E : int { a, b, c }
int[] abc = cast(int[]) [ EnumMembers!E ];

Cast is not necessary if the type of the variable is inferred. See the example below.

Examples

Create an array of enumerated values

enum Sqrts : real
{
    one = 1,
    two = 1.41421,
    three = 1.73205
}
auto sqrts = [EnumMembers!Sqrts];
assert(sqrts == [Sqrts.one, Sqrts.two, Sqrts.three]);

A generic function rank(v) in the following example uses this template for finding a member e in an enumerated type E.

// Returns i if e is the i-th enumerator of E.
static size_t rank(E)(E e)
if (is(E == enum))
{
    static foreach (i, member; EnumMembers!E)
    {
        if (e == member)
            return i;
    }
    assert(0, "Not an enum member");
}

enum Mode
{
    read = 1,
    write = 2,
    map = 4
}
assert(rank(Mode.read) == 0);
assert(rank(Mode.write) == 1);
assert(rank(Mode.map) == 2);

Use EnumMembers to generate a switch statement using static foreach.

import std.conv : to;
class FooClass
{
    string calledMethod;
    void foo() @safe { calledMethod = "foo"; }
    void bar() @safe { calledMethod = "bar"; }
    void baz() @safe { calledMethod = "baz"; }
}

enum FooEnum { foo, bar, baz }

auto var = FooEnum.bar;
auto fooObj = new FooClass();
s: final switch (var)
{
    static foreach (member; EnumMembers!FooEnum)
    {
        case member: // Generate a case for each enum value.
            // Call fooObj.{name of enum value}().
            __traits(getMember, fooObj, to!string(member))();
            break s;
    }
}
// As we pass in FooEnum.bar, the bar() method gets called.
assert(fooObj.calledMethod == "bar");

Meta