enum to string

Lionello Lunesu lio at lunesu.remove.com
Thu Mar 12 16:04:58 PDT 2009


Nick Sabalausky wrote:
> Is there any way to do this (preferably in D1) with reflection? (ie, without 
> having to manually create a conversion func/lookup for every value of every 
> enum.)
> 
> ----------------------
> enum Shape
> {
>     Square, Circle
> }
> char[] foo(Shape s)
> {
>     // ?????
> }
> 
> // Either one of these, I don't really care which
> assert(foo(Shape.Square) == "Shape.Square");
> assert(foo(Shape.Square) == "Square");
> ----------------------
> 

You got to give it to Walter: the code is pretty clean (for C++ code anyway)

Add the attached code to src\dmd\mtype.c, line 5025 (in 
TypeEnum::dotExp, after the #endif). This now works:

import std.stdio;
enum ABC { A, B, C };

void main(string[] args)
{
   foreach(a; ABC.tupleof)
   {
     writefln(a);
   }
}

prints:
A
B
C

Of course, I'm way over my head here. I've just copied the code from 
struct.tupleof to make enum.tupleof and creating a tuple of StringExps 
insteadof DotVarExps, whatever they are....

L.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: enum_foreach.c
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20090313/99543bf6/attachment.asc>


More information about the Digitalmars-d-learn mailing list