View source code Display the source code in std/traits.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Alias std.traits.EnumMembers

Retrieves the members of an enumerated type enum E.

Declaration

alias EnumMembers(E) = EnumSpecificMembers!(__traits(allMembers,E));

Parameters

NameDescription
E An enumerated type. E may have duplicated values.

Returns

Static tuple composed of the members of the enumerated type E. The members are arranged in the same order as declared in E.

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.typetuple.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

Creating 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.
size_t rank(E)(E e)
    if (is(E == enum))
{
    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);

Authors

Walter Bright, Tomasz Stachowiak (isExpressions), Andrei Alexandrescu, Shin Fujishiro, Robert Clipsham, David Nadlinger, Kenji Hara, Shoichi Kato

License

Boost License 1.0.

Comments