Template to create a type and instantiate it
cy via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 5 22:02:13 PST 2016
On Friday, 5 February 2016 at 07:44:29 UTC, Rikki Cattermole
wrote:
> That code is completely wrong anyway.
Well, obviously it's wrong. If I don't know correct code that
will do what I want, then I can't tell you what I want using
correct code.
> But you could do:
>
> alias Derp = TFoo;
> Derp obj;
I wasn't trying to make instances of TFoo. I was trying to make a
type on the spot every time TFoo is used.
Sort of like std.functional.unaryFun!, which I found since
looking around for information about it. It looks like the key to
doing it is using "mixin" inside the template declaration itself.
Also in realizing that "template" can be treated like its own
source code for the purpose of mixins.
template Thing(alias code) {
class Thing {
int a, b;
this() {
mixin(code);
}
static Thing instance;
static this() {
instance = new Thing;
}
}
}
import std.stdio: writeln;
mixin Thing!q{
writeln("a ",this.a," b ",this.b);
};
int main() {
writeln("the instance exists... somewhere...");
return 0;
}
You could also say alias Q = Thing!... if accessing Q.instance is
important.
More information about the Digitalmars-d-learn
mailing list