Dynamic Ctors ?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 6 15:35:17 PST 2016


On 02/06/2016 10:05 AM, Voitech wrote:

 > create manually, constructor
 > for each of T... parameter types

You can use string mixins (makeCtor and makeCtors):

string makeCtor(T)() {
     import std.string : format;

     return format(q{
         this (%s t) {
             import std.stdio : writefln;
             writefln("Ctor for %%s", %s.stringof);
         }
         }, T.stringof, T.stringof);
}

// Note: Use a pragma(msg) to see what it generates:
// pragma(msg, makeCtor!int);

string makeCtors(T...)() {
     string result;
     foreach (Type; T) {
         result ~= makeCtor!Type();
     }
     return result;
}

mixin template foo(T...) {

     class Inner {
         mixin (makeCtors!T());
     }
}

mixin foo!(int, string);

void main() {
     auto i = new Inner(42);
     auto s = new Inner("hello");
}

Output:

Ctor for int
Ctor for string

Ali



More information about the Digitalmars-d-learn mailing list