Bug 7821 – std.conv.to is broken for enums

Status
RESOLVED
Resolution
DUPLICATE
Severity
major
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-04-04T11:29:00Z
Last change time
2012-04-04T17:39:37Z
Assigned to
nobody
Creator
andrej.mitrovich

Comments

Comment #0 by andrej.mitrovich — 2012-04-04T11:29:28Z
import std.conv; enum Tag { A ,AB } void main() { Tag tag1 = to!Tag("A"); // ok Tag tag2 = to!Tag("AB"); // fail } ConvException: Unexpected 'B' when converting from type string to type Tag It appears if you have an enum field name that begins with another field's name std.conv.to fails to parse it. This is a blocker for me.
Comment #1 by andrej.mitrovich — 2012-04-04T11:31:55Z
(In reply to comment #0) > This is a blocker for me. OK not a blocker, I can implement a simple template function that converts strings to fields.
Comment #2 by andrej.mitrovich — 2012-04-04T11:50:48Z
First attempt at a workaround: import std.stdio; import std.conv; import std.string; import std.traits; import std.metastrings; string toSwitch(T)() { typeof(return) result; string cases; foreach (arg; EnumMembers!T) { cases ~= "case " ~ `"` ~ to!string(arg) ~ `"` ~ ":\n"; cases ~= Format!("return %s.%s;\n", T.stringof, to!string(arg)); } result ~= " auto myTo(string input) { switch(input) { " ~ cases ~ ` default: throw new Exception(format("Can't convert '%s' to type %s.", input, ` ~ `"` ~ T.stringof ~ `"` ~ `)); } } `; return result; } template myTo(T) if (is(T == enum)) { mixin(toSwitch!T); } enum Tag { A ,AB } void main() { Tag tag1 = myTo!Tag("A"); // ok Tag tag2 = myTo!Tag("AB"); // ok Tag tag3 = myTo!Tag("ABC"); // fail, ok } Works pretty nicely even though it can be implemented much nicer. Yay D. :)
Comment #3 by yebblies — 2012-04-04T17:39:37Z
*** This issue has been marked as a duplicate of issue 4744 ***