Enum to string array
Sergey Gromov
snake.scaly at gmail.com
Thu Oct 2 18:34:10 PDT 2008
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.
More information about the Digitalmars-d-learn
mailing list