Char enum conversion

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 1 21:05:25 UTC 2021


On 1/1/21 3:27 PM, Rekel wrote:
> On Friday, 1 January 2021 at 18:27:05 UTC, Steven Schveighoffer wrote:
>>> 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.
> 
> I meant that in case this was an issue with char when templating in 
> general, as I'm quite new to it I wasnt sure if that was what you meant.

There may be some misunderstanding here. A string is an *array* and is 
not implicitly convertible from values like char.

However, an int is implicitly convertible from char.

If you have an overload set like:

void foo(string s) { writeln("string: ", s); }
void foo(int i) { writeln("int: ", i); }

foo("A"); // prints string: A
foo('A'); // prints int: 65

This is all that is happening, the overload set for `to` is either 
string or the base type of the enum (in this case int). So 'A' matches 
the int, not the string. It's not an issue with templating at all, you 
can template on a char no problem. It's just the way `to` is implemented.

My comment about not being convincing was basically a solicitation to 
see if you have a compelling case of why you would want to use a char to 
represent an enum name instead of a string. The small example you give 
is not that.

-Steve


More information about the Digitalmars-d mailing list