Getting the string representing the enum value ~ Proposal

Tom ihate at spam.com
Mon Apr 3 20:25:49 PDT 2006


This is something that has been discussed before. Don't know why it has 
been rejected though.

This feature I'd love to see implemented in D. All these kind of little 
details makes D very attractive for C/C++ programmers (some of them wish 
there was a prettier syntax for C++ and they see D as just that, in the 
beginning of course). Believe me I know people that loves this kind of 
stuff, though it would be just a little detail for some points of view, 
it's not just about saving a few lines of code, it's also about nicer 
and prettier code (avoids duplicating stuff).

Hope to hear the proposal again soon in the main newsgroup.

Regards,
--
Tom;

kris escribió:
> Ben Gardner wrote:
>> I've done that "the hard way" in C.
>> Here's an example in D:
>>
>> /////
>> import std.stdio;
>> import std.string;
>>
>> enum X {
>>   Apple,
>>   Bat,
>>   Car,
>> }
>>
>> char [][] X_names = [
>>    X.Apple : "Apple",
>>    X.Bat   : "Bat",
>>    X.Car   : "Car",
>> ];
>>
>> char [] get_X_name(X e)
>> {
>>    if ((e >= X.min) && (cast(int)e < X_names.length) &&
>>        (X_names[e] !is null)) {
>>       return X_names[e];
>>    }
>>    return ("invalid");
>> }
>>
>> X get_X_id(char [] name)
>> {
>>    for (int idx = 0; idx < X_names.length; idx++) {
>>       if ((X_names[idx] !is null) && (icmp(X_names[idx], name) == 0))
>>          return cast(X)idx;
>>    }
>>    return cast(X)-1;
>> }
>>
>> void main(char [][] args)
>> {
>>    for (int i = -1; i < 4; i++)
>>    {
>>       writef("%d = '%s'\n", i, get_X_name(cast(X)i));
>>    }
>>
>>    char [] name = "bat";
>>    writef("id for '%s' is %d\n", name, cast(int)get_X_id(name));
>> }
>> ////
>>
>> Running this produces the output:
>> -1 = 'invalid'
>> 0 = 'Apple'
>> 1 = 'Bat'
>> 2 = 'Car'
>> 3 = 'invalid'
>> id for 'bat' is 1
>>
>> Ben
>>
>> Hasan Aljudy wrote:
>>
>>> say I have an enum
>>>
>>>    enum X
>>>    {
>>>     A,
>>>     B,
>>>     C
>>>    }
>>>
>>> and I have
>>>
>>>    void someFunc( X e )
>>>    {
>>>     //.. some code
>>>    }
>>>
>>> I want to print the value of 'e' but I don't want to get a number!! I
>>> want to get a string that represents it. i.e. A or B or C
>>>
>>>
>>>    void someFunc( X e )
>>>    {
>>>       toString(e);
>>>       e.string;
>>>       e.value;
>>>       //or something like that ..
>>>    }
>>>
>>> Is there any such thing in D?
>>>
> 
> 
> I'll propose that a new property be added, somewhat like the .mangleof 
> property. Instead, a .nameof property would simply return the lexical 
> token for the named entity. Doesn't matter whether it refers to a 
> struct, class, some attribute thereof, enum types or members, whatever 
> ... the x.nameof should just return a char[] of the respective name.
> 
> Thoughts?




More information about the Digitalmars-d-learn mailing list