문제

What is the state and plans on type-safety of enums in D?

I expected

import std.stdio: writeln;

void main(string args[]) {
    enum E {x, y, z}
    E e;
    writeln(e);
    e = cast(E)3;
    writeln(e);
}

to fail to compile because of D's otherwise strong static type/range checking or at least give an RangeException when run.

To my surprise, it instead prints

cast(E)3

Is this really the preferred default behaviour for the majority of use cases? If so have anybody written some wrapper type providing more stricter range-checking preferrably in compile-time?

도움이 되었습니까?

해결책

cast means you're taking matters into your own hands, and you can do anything with it - useful, like ratchet freak said, for combining flags. (Though, in those cases, I like to give an exact type and explicit values to each item to be sure everything does what I want, so enum : ubyte { x = 1, y = 2, z = 4}, that kind of thing)

Anyway, there is a way to get runtime exceptions though in a case like this: use std.conv.to:

import std.conv;
import std.stdio;

void main() {
    enum E {x, y, z}
    E e;
    writeln(e);
    e = to!E(2); // gives z, whereas to!E(3) throws an exception
    writeln(e);
}

Cool fact: to!E(string) also works. to!E("x") == E.x, and to!string(E.x) == "x".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top