Getting the string representing the enum value ~ Proposal
kris
foo at bar.com
Sun Apr 2 17:37:00 PDT 2006
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