final switch and straight integers

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Apr 21 05:45:34 PDT 2016


On 4/19/16 6:04 PM, Stefan Koch wrote:
> On Tuesday, 19 April 2016 at 14:53:18 UTC, Steven Schveighoffer wrote:
>
>> or we
>> should do away with requiring handling all enum cases.
>
>
> Are you suggesting getting rid of final switch ?

No, what I'm suggesting is that final switch behave consistently. For 
integers, final switch doesn't require all possible values be handled, 
but for enums it does. One way to make this consistent is to not require 
all enums be handled. I'm not suggesting that this is the best answer, 
just that it is a possible way to square the inconsistency.

Note that even with final switch on an enum, you have issues, especially 
if the enum is considered to be a bitfield:

enum bitfield {
    flag1 = 1 << 0,
    flag2 = 1 << 1
}

...

void foo(bitfield x)
final switch(x)
{
    case flag1:
      writeln("flag1");
      break;
    case flag2:
      writeln("flag2");
      break;
}

This compiles, but doesn't handle flag1 | flag2. So final switch isn't 
helping to cover all cases.

In other cases, you may have a member of an enum that isn't ever used as 
a value, but you have to cover it:

enum message {
     foo,
     bar,
     mask = foo | bar
}

final switch is nice when you fit into the use case. When not, you have 
to fall back to normal switch. I find many times wanting to use final 
switch but having to follow the rules would make it look silly.

-Steve


More information about the Digitalmars-d mailing list