Bug 7637 – writeln doesn't take custom toString into account
Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-03-03T17:11:00Z
Last change time
2012-04-20T09:19:13Z
Keywords
accepts-invalid
Assigned to
nobody
Creator
andrej.mitrovich
Comments
Comment #0 by andrej.mitrovich — 2012-03-03T17:11:49Z
import std.stdio;
struct Foo {
string toString(bool x) { return ""; }
}
void main()
{
Foo foo;
writeln(foo.toString()); // nogo: ok
writeln(foo); // compiles
}
The second writeln() call shouldn't compile. It seems writeln uses a default toString if it doesn't find a toString() function that takes exactly zero arguments.
Note that it will call the custom toString if 'x' has a default argument.
Comment #1 by lovelydear — 2012-04-19T09:46:20Z
The above code doesn't compile on 2.059 Win32.
However this compiles:
import std.stdio;
struct Foo {
string toString(bool x) { return ""; }
}
void main()
{
Foo foo;
writeln(foo.toString(true)); // nogo: ok
writeln(foo); // compiles
}
PS E:\DigitalMars\dmd2\samples> rdmd bug.d
toto
Foo()
Comment #2 by andrej.mitrovich — 2012-04-19T10:11:26Z
(In reply to comment #1)
> The above code doesn't compile on 2.059 Win32.
nogo in a comment means that line doesn't compile. The second call is the interesting one.
Comment #3 by k.hara.pg — 2012-04-20T03:11:31Z
This is current std.format design, not accepts-invalid bug.
Today, std.format.formatValue (it is internally used by writeln and writefln) only supports following toString specializations:
http://dlang.org/phobos/std_format.html
----
const void toString(scope void delegate(const(char)[]) sink, FormatSpec fmt);
const void toString(scope void delegate(const(char)[]) sink, string fmt);
const void toString(scope void delegate(const(char)[]) sink);
const string toString();
If there is no toString() that matches required signatures, formatValue formats the object with 'TypeName(field-formattings-separeted-with-comma)', instead of reporting 'invalid toString signature detected' error.
There is two design decides:
- Ignoring invalid toString makes more user-defined types formattable.
- Shouldn't prevent any kind of toString that user really wants.
Comment #4 by andrej.mitrovich — 2012-04-20T09:19:13Z