Generate toString() method at compile time

Ary Borenszweig ary at esperanto.org.ar
Wed Mar 26 08:01:33 PDT 2014


On 3/26/14, 11:47 AM, Adam D. Ruppe wrote:
> On Wednesday, 26 March 2014 at 14:16:08 UTC, Ary Borenszweig wrote:
>> I'd like to generate a toString() method for my classes. For example:
>
> Try this:
>
>    override string toString() {
>          import std.conv;
>          string s;
>          s ~= this.classinfo.name ~ "(";
>          foreach(idx, val; this.tupleof) {
>                  if(idx) s ~= ", ";
>                  s ~= this.tupleof[idx].stringof[5 .. $];
>                  s ~= " = ";
>                  s ~= to!string(val);
>          }
>          s ~= ")";
>          return s;
>    }
>
> add that method to Foo.
>
> $ ./test58
> test58.Foo(x = 1, y = 2)

A small question: tupleof seems to return a tuple of values. So 
this.tupleof[idx] would return a value. However when you do 
this.tupleof[idx].stringof that somehow gets the name of the field. 
Shouldn't it return the name of the value? I'm confused.


More information about the Digitalmars-d-learn mailing list