Using std.conv.to with enum that is based on string type

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Sat Jul 19 11:23:25 PDT 2014


On 07/19/2014 09:29 AM, Uranuz wrote:

 > In this case I see than we exactly doing something special when
 > converting to string type.

Ok, now I see what you mean. The title of the thread is a little 
confusing because actually you are not talking only about string-based 
enums.

The issue is, since there is already .stringof to get the string 
representation of the identifier, to!string should be for the value. So 
there are two WATs in the following program for the two enums with int 
and string base types:

import std.conv;

struct MyStruct
{
     string s;
}

void main()
{
     enum I : int { a = 1 }

     assert(I.a.stringof == "a");  // the identifier
     assert(I.a == 1);             // the value
     assert(I.a.to!int == 1);      // the value
     assert(I.a.to!double == 1);   // the value
     // ... same for other to!T ...
     assert(I.a.to!string == "a"); // WAT?

     enum S : string { a = "hello" }

     assert(S.a.stringof == "a");                   // the identifier
     assert(S.a == "hello");                        // the value
     assert(S.a.to!MyStruct == MyStruct("hello"));  // the value
     // ... same for other to!T ...
     assert(S.a.to!string == "a");                  // WAT?
}

I agree with that representation of the problem but as bearophile says, 
it is probably too late to make such a change.

Ali



More information about the Digitalmars-d mailing list