Why does toString() exist? It seems useless.
Steven Schveighoffer
schveiguy at yahoo.com
Mon Aug 18 07:28:36 PDT 2008
"Don" wrote
>I cannot understand the rationale for a toString() member function which
>doesn't support formatting.
>
> I don't think I've ever made a class which only has a single format
> option. If the class contains any integers, I want to specify whether it
> should use hex or decimal, leading zeros, sign. If it contains floating
> point numbers, it's number of digits, scientific notation, hex or decimal,
> and what to do with NaNs. And of course there are locales.
>
> Seriously, I cannot remember ever not having this requirement, so I cannot
> imagine a use for toString().
>
> C++ got around this by giving state to the iostream classes. As far as I
> can tell, neither Phobos nor Tango provide any support at all.
>
> Practical example: BigInt (which I'm developing in both Tango and Phobos).
> It is a struct. How can it support I/O? I can't work out how to do it in
> either library.
As you have discovered, it is for simple debugging.
However, it's not even close to as useful as Java, where if you combine a
string with an object, it automatically calls the toString function.
As far as supporting an output method, I think toString is completely the
wrong way to look at it. A simple example is a container class, such as a
vector of ints.
Let's say you are outputting a vector of ints every time it has changed.
What ends up happening is you build a (possibly huge) string every time you
output the vector, and then are throwing the string away! When all you
really need is about 20 bytes of stack space to create the individual int
strings and then output to an i/o function.
Even with a format string, that doesn't solve this problem.
What I would like to see is an output method in Object that looks like:
int output(int delegate(char[] x) sink, char[] fmt = null);
And something like how 'toString' works in a struct (where there is an
xoutput function in the struct typeinfo class).
This is a generic solution, it would be customized to the appropriate i/o
library of Tango or Phobos. Possibly the format strings would be different
based on the I/O (i.e. Phobos uses printf style formatting constructs, Tango
uses .NET style).
-Steve
More information about the Digitalmars-d-learn
mailing list