View source code
Display the source code in std/traits.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
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.

Alias std.traits.EnumMembers

Retrieves the members of an enumerated type enum E.

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

Example

Create an array of enumerated values

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

Example

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
}
writeln(rank(Mode.read)); // 0
writeln(rank(Mode.write)); // 1
writeln(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.