Feature request: enum init shouldn't create a new enumeration
Jonathan M Davis
jmdavisProg at gmx.com
Sat Oct 13 13:25:43 PDT 2012
On Saturday, October 13, 2012 17:39:23 Tommi wrote:
> I'd like to be able to specify a default value for a named enum,
> E.init, without creating a new enumeration. There are three
> reasons:
> 1) Default initializing enum variables to an "invalid" value
> 2) Being able to use 'final switch' without the 'init' case
> 3) "Invalid" init value wouldn't affect E.min or E.max
>
> Here's what currently happens:
>
> enum MyEnum
> {
> init = -123,
> first = 0,
> second = 1
> }
>
> void main()
> {
> static assert(MyEnum.min == -123);
>
> MyEnum me;
>
> final switch (me)
> {
> case MyEnum.first: break;
> case MyEnum.second: break;
> case MyEnum.init: // I'm forced to specify init case too
> }
> }
>
> This is what I'd like to happen:
>
> enum MyEnum
> {
> init = -123,
> first = 0,
> second = 1
> }
>
> void main()
> {
> static assert(MyEnum.min == 0); // no effect on min/max
>
> MyEnum me;
>
> final switch (me) // no init case necessary nor allowed
> {
> case MyEnum.first: break;
> case MyEnum.second: break;
> }
> }
Think about that for a moment. What happens when that final switch statement is
actually run? Which statement would MyEnum.init use? The whole point of final
switch is that the compile _knows_ that every single value for that type has a
case. With your suggestion, it specifically _doesn't_ have a case for one of
the type's values. And it _will_ happen at some point that you'll hit a switch
like that with the init value rather than a valid one. I don't see how that
can possibly work or make any sense at all.
And remember, that in many cases, T.init is considered to be perfectly valid.
By allowing a final switch _not_ to have it, it then becomes easy to forget to
add a case for it when you _need_ to, completely defeating the purpose of the
final switch (to make it so that both you and the compiler know that all of the
possible values are accounted for).
- Jonathan M Davis
More information about the Digitalmars-d
mailing list