Bug 6231 – [patch] std.conv.to/std.format.: Structs with toString and isInputRange match multiple templates.

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P3
Component
phobos
Product
D
Version
D2
Platform
Other
OS
Windows
Creation time
2011-06-30T11:27:00Z
Last change time
2012-06-14T02:38:46Z
Keywords
patch
Assigned to
nobody
Creator
sandford

Comments

Comment #0 by sandford — 2011-06-30T11:27:03Z
If a struct defines a custom toString method and satisfies isInputRange, then to!string(Struct) will match multiple toImpl templates. The solution is to add an extra template constraint to the input range toImpl to detect structs with custom toString methods. [Line 194 in DMD 2.053] T toImpl(T, S)(S s, in T leftBracket = "[", in T separator = ", ", in T rightBracket = "]") if (isSomeString!T && !isSomeChar!(ElementType!S) && (isInputRange!S || isInputRange!(Unqual!S)) ) -This is the constraint to add. && !(is(S == struct) && is(typeof(&S.init.toString))) )
Comment #1 by sandford — 2011-06-30T12:04:07Z
std.format.formatRange also suffers from a similar problem, although in this case it is one of choosing a non-character range over the custom toString routine. [Line 1171 in format.d in DMD 2.053] void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f) if (isInputRange!T && !isSomeString!T The extra condition: && !(is(T == struct) && is(typeof(&T.init.toString))) ) And the toString exception needs to added to Line 1474 void formatValue(Writer, T, Char)(Writer w, T val, ref FormatSpec!Char f) if (is(T == struct) && (!isInputRange!T || is(typeof(&T.init.toString))) ) By the way, I like the idea of void toString(void delegate(const(char)[]) sink, FormatSpec fmt); void toString(void delegate(const(char)[]) sink, string fmt); but are which one is preferred? And if/when is Object going to switch over?
Comment #2 by k.hara.pg — 2012-06-14T02:38:46Z
Now almost bugs around formatting were fixed. (In reply to comment #1) > By the way, I like the idea of > void toString(void delegate(const(char)[]) sink, FormatSpec fmt); > void toString(void delegate(const(char)[]) sink, string fmt); > but are which one is preferred? And if/when is Object going to switch over? Getting FormatSpec version is most specialized than others, so is preferred. And such enhanced toStrings are priority than Object.toString() in class.