D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 8012 - Add .length field to enums or provide helper function to Phobos
Summary: Add .length field to enums or provide helper function to Phobos
Status: RESOLVED DUPLICATE of issue 4997
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2012-05-01 13:44 UTC by Andrej Mitrovic
Modified: 2012-05-01 15:39 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Andrej Mitrovic 2012-05-01 13:44:17 UTC
My use-case:

enum Foo
{
    x,
    z,
    y
}

enum Bar : Foo
{
    x = Foo.x,
    y = Foo.y,
    z = Foo.z
}

I really want to ensure that when I update Foo I will be forced to update Bar (IOW get a compile-time error). If enums had a .length property then I could easily add a static assert:

static assert(Foo.length == Bar.length);

As a workaround (if the proposal is rejected), we might add this template to Phobos:

template EnumLength(E)
    if (is(E == enum))
{
    enum EnumLength = [__traits(allMembers, E)].length;
}

Used like so:
static assert(EnumLength!Foo == EnumLength!Bar);

I'd prefer having .length over instantiating templates, but either is fine for me.
Comment 1 Andrej Mitrovic 2012-05-01 13:47:14 UTC
Oops I marked it wrong. It's an enhancement request.
Comment 2 bearophile_hugs 2012-05-01 15:27:54 UTC
(In reply to comment #0)

Dupe of Issue 4997 ?


> template EnumLength(E)
>     if (is(E == enum))
> {
>     enum EnumLength = [__traits(allMembers, E)].length;
> }

This is enough, no need to create an array:

template EnumLength(E) if (is(E == enum))
{
    enum EnumLength = __traits(allMembers, E).length;
}


But your problem is probably solved in another way, creating an "enum duplicator".
Comment 3 Andrej Mitrovic 2012-05-01 15:39:37 UTC
(In reply to comment #2)
> (In reply to comment #0)
> 
> Dupe of Issue 4997 ?

Yeah, I'll close this then.

> This is enough, no need to create an array:
> 
> template EnumLength(E) if (is(E == enum))
> {
>     enum EnumLength = __traits(allMembers, E).length;
> }

Thanks, I forgot tuples have length.

> But your problem is probably solved in another way, creating an "enum
> duplicator".

Well in my real code the "subtyped" enum has different field names but the same values as another enum. Anyway it's not an issue as long as I can get the length of the enum.

*** This issue has been marked as a duplicate of issue 4997 ***