Getting the string representing the enum value ~ Proposal

Hasan Aljudy hasan.aljudy at gmail.com
Sun Apr 2 21:56:41 PDT 2006


Ben Gardner wrote:
> kris wrote:
> 
>>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?
> 
> 
> This would be easy implement if the enum value is known at compile time
> (ie, X.Apple.nameof).
> 
> But to do this for an unknown enum value would require that a complete
> string table be defined for every enum.
> 
> void foo(X e)
> {
>    writef("the enum name is %s\n", e.nameof);
> }
> 
> I suppose that the compiler would be smart enough to drop the string
> table if it is never used, so there is no harm in defining the table for
> all enums.
> 
> Ben

Yeah, I think it's actually very easy to implement, I don't see why dmd 
doesn't do it.

for every enum X, the parser can very easily identify EnumMembers and 
generate a table along the lines of:

     char[] [X] XMemberToStringTable;

     static this()
     {
         XMemberToStringTable[X.A] = "A";
         XMemberToStringTable[X.B] = "B";
         XMemberToStringTable[X.C] = "C";
     }

     char[] XtoString( X a )
     {
         return XMemberToStringTable[a];
     }

not hard at all.




More information about the Digitalmars-d-learn mailing list