On Monday, 7 April 2014 at 21:02:04 UTC, Andrei Alexandrescu wrote:
This program compiles and flag free and no cast in sight but fails at runtime. Textbook example of unsound type design.

import std.stdio;

enum A { x = 2, y = 4 }

void main()
    A a = A.x | A.y;
    final switch (a)
        case A.x: break;
        case A.y: break;

The "|" operator converts back to an A. It shouldn't. In this case it provides a value not only outside the enum range, but even greater than A.max (when converted to integer).

I'm fine with "yes, it's unsound, but we wanted to do flags and we couldn't find a better solution", but this "it's deliberate and it's good" I just find difficult to get behind.


Yeah, I've seen this happen before. I think we could actually introduce a little more type safety on enums without a great deal of breakage. It would be nice to have a final switch give you as much of a guarantee about what it's doing as it can.

Reply via email to