Alias std.traits.EnumMembers
Retrieves the members of an enumerated type enum E
.
Parameters
Name | Description |
---|---|
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
.
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, 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 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
Example
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.
writeln(fooObj .calledMethod); // "bar"
Authors
Walter Bright,
Tomasz Stachowiak (isExpressions
),
Andrei Alexandrescu,
Shin Fujishiro,
Robert Clipsham,
David Nadlinger,
Kenji Hara,
Shoichi Kato