Enum to string array

Spacen Jasset spacenjasset at yahoo.co.uk
Fri Oct 3 06:44:58 PDT 2008


Sergey Gromov wrote:
> Wed, 01 Oct 2008 17:03:26 +0100,
> Spacen Jasset wrote:
>> ylixir wrote:
>>> maybe an associative array is what you are looking for?
>>>
>>> something like:
>>>
>>> char[][Symbols] theArray;
>>>
>>> theArray[Symbols.CYCLIC_FORWARD] = "Cycle Forward";
>>> theArray[Symbols.CYCLIC_BACKWARD] = "Cycle Backwards";
>>>
>>> writefln(theArray[Symbols.CYCLIC_FORWARD]); //prints "Cycle Forward"
>>> writefln(theArray[Symbols.CYCLIC_BACKWARDS]); //prints "Cycle Backwards"
>> Yes indeed. But I really would like it to map the other way, also it's a 
>> bit akward as you have to add an enum entry and a AA aray entry. But 
>> it's defiantly a possible solution. At the moment I have parallel 
>> arrays, which is also a bit risky.
> 
> Here's one possible solution:
> 
> import std.stdio: writeln;
> 
> string makeList(R...)(string first, R rest)
> {
>     static if (rest.length)
>         return first ~ ", " ~ makeList(rest);
>     else
>         return first;
> }
> 
> string[] toArray(R...)(string first, R rest)
> {
>     static if (rest.length)
>         return [first] ~ toArray(rest);
>     else
>         return [first];
> }
> 
> template TwoWayEnum(Fields...)
> {
>     mixin("enum { " ~ makeList(Fields) ~ "};");
> 
>     string toString(int el)
>     {
>         return toArray(Fields)[el];
>     }
> 
>     int fromString(string s)
>     {
>         int fromString(R...)(int id, string first, R rest)
>         {
>             if (first == s)
>                 return id;
>             else
>             {
>                 static if (rest.length)
>                     return fromString(id+1, rest);
>                 else
>                     throw new Exception("bad name");
>             }
>         }
> 
>         return fromString(0, Fields);
>     }
> }
> 
> void main()
> {
>     alias TwoWayEnum!("a"[],"b"[],"c"[],"d"[]) abcd;
>     writeln(abcd.c);
>     writeln(abcd.toString(abcd.c));
>     writeln(abcd.fromString("c"));
> }
> 
> One complication here is that you must specify element names with square 
> brackets at the end which converts them into slices, otherwise toArray 
> stuff doesn't work.
Ah thanks. I will try this out. I must say that I can't find 
documentation on the mixin("") form on the official site.


More information about the Digitalmars-d-learn mailing list