override toString() for a tuple?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 3 23:04:02 PDT 2014


On Wed, 04 Jun 2014 05:35:18 +0000
Steve D via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> Is it possible to override std tuple's toString format?
>
> so that
>          auto a = tuple("hello",1,2,3);
>          writeln(a);
>
> prints
>          ("hello", 1, 2, 3)
> and not
>          Tuple!(string, int, int, int)("hello", 1, 2, 3)
>
>
> I'm aware I could write a custom formatter function, but it would
> be nice not to
> have to use such a function for every tuple printed by the
> program.
> Overriding toString() one time in program (if possible) would
> give the ideal default behaviour. (I would duplicate the current
> typecons.d toString() and strip off the prefix)
>
> thanks for any help

toString is a member of Tuple, and there's no way to override that externally.
You could create a wrapper struct for a Tuple whose toString method did what
you want, and you could just create a function which generated the string that
you wanted that you used whenever printing out a Tuple, but there is no way to
globally override Tuple's toString.

The closest that you could do to overriding Tuple's toString in one place
would be to write your own wrappers for whatever printing functions you want
to use, have them detect when they're given a Tuple, and then print them the
way that you want and pass everything else directly on to writeln or whatever
it is you're wrapping. Then, the print functions would take care of it for
you, but writing such a function wouldn't exactly be fun.

If you're really determined to print tuples differently, you _could_ simply
copy std.typecons.Tuple to your own code and alter it to do what you want.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list