Char enum conversion

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 1 17:59:30 UTC 2021


On 1/1/21 12:17 PM, Rekel wrote:
> I'm surprised char to enum conversion is currently not possible.
> This, as char[] & string conversion to enum is supported.
> 
>> enum E{A, B}
>> void main()
>> char[] a = ['A'];
>> a.to!E.writeln;
>> "A".to!E.writeln;
>> 'A'.to!E.writeln; // Crash
>> }
> 
> The last line crashes with:
>> std.conv.ConvException at C:\D\dmd2\windows\bin\..\..\src\phobos\std\conv.d(2058): 
>> Value (A) does not match any member value of enum 'Enum'

So what's happening here is that std.conv.to is treating your 'A' as an 
integer. What you are doing is really:

65.to!E.writeln; // 'A' is really a octet of 65

That char/wchar/dchar are treated as a standard implicit-convertible 
integer type is one of the failings of D I think.

Another gotcha to watch out for, if your enum is string-based, there is 
NO WAY to use std.conv to convert from the base string to the enum type, 
it only goes by enum names.

-Steve


More information about the Digitalmars-d mailing list