Enum conversion

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 21 20:01:34 UTC 2020


On 4/21/20 2:09 PM, tsbockman wrote:
>> conversely what is the right way of going the other way:
>>
>> cast(ZoneNumber)1
>> to!ZoneNumber(1)
> 
> Use `to` except where you can gaurantee that the input value maps to a 
> valid enum member, because `cast` does not check your work:
> 
>      writeln(cast(ZoneNumber)17); // breaks the type system
>      writeln(to!ZoneNumber(17)); // throws a ConvException: Value (17) 
> does not match any member value of enum 'ZoneNumber'
> 
> So, `cast` is faster, but unsafe. `to` is slower, but protects the 
> enum's invariant.

I just want to correct this and say there isn't a type system 
requirement for the enum to be only one of the selected values, even in 
safe code.

e.g.:

enum flags {
   one = 1,
   two = 2,
}

flags f = flags.one | flags.two; // ok
++f; // ok also

In essence, an enum acts as a derived type with named constants.

Also, there is one situation where you can't use to -- a string-based enum:

enum sym : string {
    s = "s value",
    y = "y value"
}

auto a = cast(sym)"s value"; // ok
assert(a == sym.s);

auto b = to!sym("s value"); // runtime error

This is because to!someEnum(string) is specialized to look at the enum 
names only, not the values.

-Steve


More information about the Digitalmars-d-learn mailing list