[Issue 9821] Smarter conversion of strings to enums

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Mar 26 16:43:28 PDT 2013


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



--- Comment #2 from Jared Miller <jared at economicmodeling.com> 2013-03-26 16:43:27 PDT ---
Perhaps I'm being naive, but why not modify the current string-to-enum parse()
overload so that it (1) first tries to convert using enum member names, as it
currently does, and *only if* that fails, then (2) tries to convert the string
to the enum base type?

The current functionality would remain the same, except that the conversion
would succeed instead of failing in those cases where a string => base type =>
enum conversion is possible. (Sorry if this isn't the formal way of submitting
a patch; it's more of an explanation of what I mean.)

2126,2129c2126,2148
< 
<     throw new ConvException(
<         Target.stringof ~ " does not have a member named '"
<         ~ to!string(s) ~ "'");
---
>     else
>     {
>         OriginalType!Target baseVal;
>         try {
>             baseVal = to!(OriginalType!Target)(s);
>         }
>         catch(ConvException e) {
>             throw new ConvException(
>                 "'" ~ to!string(s) ~ "' is not a member name of " 
>                 ~ Target.stringof ~ " and is not convertible to "
>                 ~ (OriginalType!Target).stringof );
>         }
>         if(countUntil([EnumMembers!Target], baseVal) != -1)
>         {
>             return cast(Target)(baseVal);
>         }
>         else 
>         {
>             throw new ConvException(
>                 "'" ~ to!string(s) ~ "' is not a member name or value of "
>                 ~ Target.stringof);
>         }
>     }

If this is not desirable, I would be okay with closing this issue and filing
one for std.csv.csvReader to work around it, since that's mainly where it
really causes problems (and possibly in other deserialization code like
std.json too). At my workplace we've hit the same issue with reading from
databases and have a special case to handle enums.

-- 
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