07-Jan-2013 00:02, Dmitry Olshansky пишет:
06-Jan-2013 23:55, Philippe Sigaud пишет:
On Sun, Jan 6, 2013 at 6:49 PM, Dmitry Olshansky <dmitry.o...@gmail.com
<mailto:dmitry.o...@gmail.com>> wrote:
Regarding toString there is a better signature that avoids useless
allocations:
void toString(scope void delegate(const (char)[]) sink);
It takes a delegate to output string representation directly to the
destination via 'sink' delegate (that may e.g. write chars to file).
Plus the 'scope' part of declaration avoids allocating the said
delegate on the heap.
I'd even say that string toString(); is an artifact of the past,
instead to!string should be used (if allocating a string is fine).
I know you explained that already, but see, that again slipped my mind.
This toString(sink) thingy seems cool, but is there a documentation on
it somewhere? Without a related doc, I fear no one will know this exists.
Guess I need to find the original on toString and bit-blit it over with
this new sink thingy ;)
There is a short note in object.d:
...
string toString();
Convert Object to a human readable string.
...
That is any class may override it.
However the real relevant golden bit of information is buried after a
row of formatValue templates (that hardly makes any sense to newcomers)
at the bottom of std.format page:
(http://dlang.org/phobos/std_format.html)
Aggregates (struct, union, class, and interface) are basically formatted
by calling toString.
toString should have one of the following signatures:
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();
So it's quite flexible. Even better then I've been advertising it.
Note that classes are covered. I bet it can call virtual functions
through base reference if base defines the new variation of toString.
The problem is if it's going to be extended to wchar/dchar... At least
wchar is useful on Windows.
But the real fun is that I fail to find any real description of toString
in the docs for d-p-l website!
The only files in d-p-l site where it is found in are:
- errors.dd:
... class Error has a pure virtual a function called toString() which
produces a char[] with a human readable description of the error.)
Nothing useful and it's out of date! It returns a string (immutable)
these days.
- lazy-evaluation.dd uses as an example of expensive computation and has
the form of toString(i) where i is an int (wtf?!).
Probably horribly out of date as it should use either format or to!string.
- tempalte.dd uses std.string.toString as an example (same as in lazy?)
and it's again an out of date piece of crap.
And a couple more files call it here and there (e.g. windows.dd to
display exception message box).
--
Dmitry Olshansky