Casting from an enum type to another enum type

Roland Hadinger via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 24 12:13:29 PDT 2015


On Wednesday, 24 June 2015 at 18:16:42 UTC, Meta wrote:
> std.conv.to really should be able to do this, but I guess not 
> many people have needed to do this. You can write an 
> "extension" to `to` which does it for you:
>
> import std.traits;
>
> auto to(To, From)(From f)
> if (is(From == enum) && is(To == enum) && is(OriginalType!From 
> : OriginalType!To))
> {
>     return cast(To)f;
> }

Thanks, that works!

I'll add this to my project's 'helpers' module, with the "return" 
line replaced by:

     foreach (m; EnumMembers!To) {
         if (m == f)
             return m;
     }
     throw new ConvException("Value not in enum");



More information about the Digitalmars-d-learn mailing list