[Issue 12701] New: Allow disabled default construction for enums

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sun May 4 10:45:48 PDT 2014


https://issues.dlang.org/show_bug.cgi?id=12701

          Issue ID: 12701
           Summary: Allow disabled default construction for enums
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: DMD
          Assignee: nobody at puremagic.com
          Reporter: andrej.mitrovich at gmail.com

Structs have a special feature which is good for catching some bugs:

-----
struct ActionStruct
{
    @disable this();
    this(int state) { }
}

void main()
{
    ActionStruct as;  // error!
}
-----

Enums could also use this feature. Currently we can implement a default invalid
state for enums by defining a special sentinel value as the first member, e.g.:

-----
enum Action
{
    invalid, create, destroy
}

Action action;
...
assert(action != Action.invalid, "Uninitialized action");
-----

But the problem is the sentinel value propagates to all usage sites, for
example:

-----
enum Action
{
    invalid,  // sentinel
    create,
    destroy,
}

void make1(Action action)
{
    final switch (action) with (Action)
    {
        case invalid: assert(0);  // must list it in a final switch
        case create, destroy:
    }
}

void make2(Action action)
{
    final switch (action) with (Action)
    {
        case invalid: assert(0);  // must list it in a final switch
        case create, destroy:
    }
}

void main()
{
    Action action;
    make1(action);
    make2(action);
}
-----

If we had a way to mark default construction of enums as disabled then we could
avoid doing checks at every usage site.

The first syntax that comes to mind is using @disable for the first member:

-----
enum Action
{
    @disable invalid,
    create,
    destroy,
}

void make1(Action action)
{
    final switch (action) with (Action)
    {
        // does not have to list disabled member
        case create, destroy:
    }
}

void make2(Action action)
{
    final switch (action) with (Action)
    {
        // does not have to list disabled member
        case create, destroy:
    }
}

void main()
{
    Action action;  // error here at compile-time
    make1(action);
    make2(action);
}
-----

--


More information about the Digitalmars-d-bugs mailing list