Currently to get the order/index of an enum member to be done in loop which is slow. Provide such member will speedup the lookup
enum Foo
{
one=100, // First order/index=0
two=399, // Next is 1
...
}
auto checkingMember = Foo.two;
size_t index;
foreach (e; EnumMembers!Foo)
{
if (e == checkingMember)
return index;
index++;
}
One of the use case is provide a set of Foo using ubyte/ushort/uint/ulong
struct Set(E)
{
void set(Foo e)
{
v |= 1 << e.order;
}
bool isSet(Foo e)
{
return (v & (1 << e.order)) != 0;
}
More...functions
uint v;
}
Comment #1 by apz28 — 2024-05-06T13:28:12Z
The value is also needed to be known at compile time
static assert(Foo.one.order == 0);
static assert(Foo.two.order == 1);
Comment #2 by nick — 2024-05-06T15:59:18Z
(In reply to apham from comment #0)
> void set(Foo e)
> {
> v |= 1 << e.order;
> }
>
> bool isSet(Foo e)
> {
> return (v & (1 << e.order)) != 0;
> }
It's not possible to take a runtime enum value and produce its index in an enum without some runtime overhead.
Another issue is that `e.order` is already valid code, meaning call `order(e)`.
Comment #3 by robert.schadek — 2024-12-13T19:35:09Z