Enum to string array

Gide Nwawudu gide at btinternet.com
Wed Oct 1 15:54:54 PDT 2008


On Wed, 01 Oct 2008 16:50:43 +0100, Spacen Jasset
<spacenjasset at yahoo.co.uk> wrote:

>bearophile wrote:
>> Spacen Jasset:
>>> enum Symbols {
>>> 		CYCLIC_FORWARD, CYCLIC_BACKWARD, CYCLIC_LEFT, etc
>>> };
>>> How could I map this into an array? (or vice-versa) must I use a switch 
>>> statement, or an enum -> string mapping array?
>> 
>> You can create a template mixin that given the list of names as strings, defines an enum and its array of strings, to map index => symbol. You can also add the opposite mapping, letting it create a switch at compile time, or an associative array, or (but this is often overkill) a perfect hash.
>> 
>> If you need help ask more :-)
>> 
>> Bye,
>> bearophile
>
>This sounds interesting. Can you give me a simple example of this. I 
>don't really deal in mixins and templates much at the moment, so I 
>cannot imagine how this might be done.

The docs are here.
http://www.digitalmars.com/d/2.0/phobos/std_typecons.html

module main;

import std.stdio;
import std.typecons;

void main()
{
  mixin(defineEnum!("Direction", "North", "South", "East", "West"));	
	
  auto d = Direction.North;
  writefln(d, " = ", enumToString(d));
  enumFromString("South",d);
  writefln(d, " = ", enumToString(d));
}
	

Hope this helps.

Gide


More information about the Digitalmars-d-learn mailing list