Generate toString() method at compile time

ketmar nobodyherethismailsucks at gmail.com
Wed Mar 26 08:08:40 PDT 2014


that's what i did in a hurry. it seems to work, but the code is 
very ugly.

[/code]
import std.conv, std.stdio, std.string, std.traits;


string gen_printer (alias cn) () {
   string res = "override string toString () {\nstring res = `" ~ 
cn.stringof ~ "(`;\n";
   bool need_comma = false;
   foreach (i, m; __traits(derivedMembers, cn)) {
     static if (!isCallable!(__traits(getMember, cn, m)) /*&& m != 
"Monitor"*/) {
       if (need_comma) res ~= `res ~= ", ";`; else need_comma = 
true;
       res ~= "res~=`" ~ m ~ " = `~to!string(" ~ m ~ ");";
     }
   }
   res ~= "res~=`)`;\n";
   res ~= "return res;\n}\n";
   return res;
}


class Foo {
   int x;
   int y;

   void test () {}

   mixin(gen_printer!Foo);
}


void main () {
   auto foo = new Foo;
   foo.x = 1;
   foo.y = 2;
   writefln("%s", foo); // prints "Foo(x = 1, y = 2)"
}
[/code]


More information about the Digitalmars-d-learn mailing list