Char enum conversion

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 1 18:27:05 UTC 2021


On 1/1/21 1:11 PM, Rekel wrote:
> On Friday, 1 January 2021 at 17:59:30 UTC, Steven Schveighoffer wrote:
>> 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.
> 
> I see why that makes sense ascii wise, however, does that ruin 
> templating for chars?

It's not. It's templating based on the base type.

when passed a variable that's an enum, `to` looks at 2 possibilities:
1. The type is a string -- match against the names of the enum values
2. The type is implicitly convertible to the enum base type, look up 
based on the base type.

Since char is not a string, but it's implicitly convertible to int 
(which is the default base type for enums), it uses the second overload.

> That would seem very problematic.

I'd have to see a more compelling example in order to agree. Using 'A' 
instead of "A" isn't that convincing.

Note, that if 'A' is in a variable, you can generate a "string" based on it:

auto nameToLookup = (&var)[0 .. 1];
nameToLookup.to!E.writeln;

> 
>> 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.
> 
> Im unsure about what you mean here. Do you mean that an enum with 
> strings as assigned values cannot be converted to using any of the 
> assigned strings? If so, how come it does work using integers?

So for example:

enum X : string
{
    Foo = "FOO",
    Bar = "BAR"
}

// 
std.conv.ConvException@/dlang/dmd/linux/bin64/../../src/phobos/std/conv.d(2819): 
X does not have a member named 'FOO'
auto val = "FOO".to!X;

// ok
auto val2 = "Foo".to!X;

How come it works for integers? Because integers are not strings, so it 
can distinguish what you want. When both case 1 and case 2 above are the 
same type, it has to pick one.

-Steve


More information about the Digitalmars-d mailing list