[Issue 9821] Smarter conversion of strings to enums

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Mar 27 12:11:29 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=9821



--- Comment #7 from Jared Miller <jared at economicmodeling.com> 2013-03-27 12:11:26 PDT ---
(In reply to comment #6)
> Then just use to with the base type. And if you're dealing with generic code or
> don't want to hard code what the base type is, then use
> std.traits.OriginalType:
> 
> to!(OriginalType!MyEnum)(str);

Right, that gets me to the base type. Eventually I want the enum type, so at
minimum I need to do:

// Naive, unless I check that the value is a member
MyEnum e = cast(MyEnum)(to!(OriginalType!MyEnum)(str));
// Strict
MyEnum e = to!MyEnum(to!(OriginalType!MyEnum)(str));

So, it's not hard, it's just always a special case. Some "expected" things
don't work: 

MyEnum { Foo = 1, Bar = 7 }
MyEnum e2 = to!MyEnum("7"); // throws
readf("%d", &e1);           // error: no matching unformatValue
readf("%d", &cast(int)e1);  // ok, works like C, avoids proper checks
writef("%d", e1);           // ok

Are my expectations just odd? Very possible :) I deal with a lot of data
munging and this little enum quirk ends up requiring special handling in every
bit of generic read/write code, unless I just ban enums entirely from all data
conversion code. C/C++ always treat them as ints and D always treats them as
member-name strings in std.conv -- you see the potential incompatibility. I
realize D has to deal with more complexity since more base types are allowed,
but it does break with tradition for integral base types.

I expected something like C# which stringifies enums to member name by default
(like D), but Enum.Parse takes strings representing *either* member name or
value. 

So, maybe std.conv could allow C#-style parsing for integral enums only. Or,
there could be a toImpl overload that's restricted to integral enums and takes
a required flag for "by name" or "by value". Also it'd be handy to have enum
overloads of unformatValue. Mainly what I don't like to see is the the default
member-name conversion creeping into other components like csvReader.

So I guess what I'm looking for is either:

(1) "No, we've thought it over and enums, regardless of base type, should
nearly always be (de)serialized by member name -- doing it by value is a rare
use case so you should write your own wrappers for anything that uses
std.conv", or

(2) "Yes, parsing string/char to integral enums by value is common enough that
components in Phobos should offer that option where appropriate."

Thanks and I hope I've made my issue clearer.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list