Getting enum from value

Kreikey via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 6 18:22:44 PDT 2017


On Saturday, 5 August 2017 at 20:11:27 UTC, Matthew Remmel wrote:
> On Saturday, 5 August 2017 at 18:26:10 UTC, Kreikey wrote:
>> On Saturday, 5 August 2017 at 15:33:57 UTC, Matthew Remmel 
>> wrote:
>>> I feel like I'm missing something, but there has to be an 
>>> easier way to convert a value into an enum than switching 
>>> over every possible value: i.e
>>>
>>> [...]
>>
>> Capitals c = cast(Capitals)"Chicago";
>> writeln(c);    // Illinois
>
> I'm annoyed that I didn't think of trying to cast it. That 
> works great if the value exists in the enum. It does something 
> weird if the value doesn't though. This is my test.d file:
>
> import std.stdio;
>
> enum Foo {
>     A = "AV",
>     B = "BV"
> }
>
> void main() {
>     Foo k = cast(Foo)"BV"; // Works and prints correctly
>
>     k = cast(Foo)"CV";
>     writeln("Type: ", typeid(k));  // Type: test.Foo
>     writeln("Value: ", k);       // Value: cast(Foo)CV
> }
> --------
> The output shows the type being the Foo enum but the value is 
> 'cast(Foo)CV'. I would of expected an error or exception to be 
> thrown if it wasn't able to cast into an actual enum member. Is 
> this something with how the enums are implemented under the 
> hood?

So I've come up with a concise way to do this. Given:

Capitals strToEnum(string myString) {
   Capitals instance = cast(Capitals)myString;
   if (![EnumMembers!Capitals].canFind(instance))
     throw new Exception("can't convert that string to that enum");
   return instance;
}

do:

Capitals c = strToEnum("Chicagoo");

Not quite a one-liner, but pretty close. Turning it into a 
template is left to the user as an exercise ;)


More information about the Digitalmars-d-learn mailing list