enum to string

Jarrett Billingsley jarrett.billingsley at gmail.com
Tue Mar 10 19:33:07 PDT 2009


On Tue, Mar 10, 2009 at 9:54 PM, Nick Sabalausky <a at a.a> wrote:
> "MIURA Masahiro" <echochamber at gmail.com> wrote in message
> news:gp730i$30e8$1 at digitalmars.com...
>> In D2:
>>
>> enum Shape: string
>> {
>>    Square = "Square",
>>    Circle = "Circle",
>> }
>>
>> void main()
>> {
>>    assert(cast(string) Shape.Square == "Square");
>> }
>
> So there's no built-in way to do this with compile-time reflection?
>
> I suppose I could work around it by creating a mixin that automatically
> generates both the enum and an enum->string routine.

In D1, that's the way you have to do it.

In D2, there is more reflection - I know you can use
__traits(allMembers, Shape) to get the names?  Or something like that?
 It's completely undocumented, of course.  There's also std.typecons
which has an enum generator that will create toString and I think
fromString functions as well.


More information about the Digitalmars-d-learn mailing list