Bug 12701 – Allow disabled default construction for enums

Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-05-04T17:45:00Z
Last change time
2016-08-29T06:27:35Z
Assigned to
nobody
Creator
andrej.mitrovich

Comments

Comment #0 by andrej.mitrovich — 2014-05-04T17:45:48Z
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); } -----
Comment #1 by andrej.mitrovich — 2016-08-29T06:27:35Z
This would add very little value, closing.