Have a template function register(T)() instantiated and executed at startup for all sub classes of a specific base class?
user1234
user1234 at 12.de
Sun Sep 21 13:43:46 UTC 2025
On Sunday, 21 September 2025 at 08:52:48 UTC, TwoOfCups wrote:
> [...]
>
> Is there any way to resolve this flaw? Is there some other
> route I could take that doesn't require a mixin?
>
> I know I can just insert a mixin and do it that way but I want
> things to look as clean as possible. Even that tiny amount of
> boiler plate bothers me a lot and this is a foundational system
> so that boiler plate will be multiplied hundreds of times I am
> expecting. Probably in the end I will just have to get over my
> aesthetic hang ups but I figured a forum post was worth a shot.
You can use the CRTP pattern [0] here:
```d
class Registerable(Derived, Base) : Base {
pragma(crt_constructor)
extern(C)
static void reg(){
writeln("Registering type ", Derived.stringof);
}
}
class Base : Registerable!(Base, Object) { }
class Derived1 : Registerable!(Derived1, Base) { }
class Derived2 : Registerable!(Derived2, Derived1) { }
```
The trick is that a a static ctor is instantiated for each
instance. Note the example is a slight adaptation from link [1].
Otherwise solutions based on static intropsection will all
involve mixins. Using mixins at the module level can be
reasonable tho (vs using them in every new derived classes). For
example:
```d
pragma(crt_constructor)
extern(C) void reg(){
foreach (m; __traits(allMembers, mixin(__MODULE__))){
static if (is(mixin(m)))
static if (is(mixin(m) : Base))
writeln("Registering type ", m.stringof);
}
}
class Base {}
class Sub0 : Base {}
class Sub1 : Sub0 {}
```
and then people just have mixin `reg()`, that your library
provides as a `q{}` string, let's say.
Anyway as I think you'll like more the CRTP solution I wont
develop more.
[0]: en.wikipedia.org/wiki/Curiously_recurring_template_pattern
[1]:
https://forum.dlang.org/post/mailman.7481.1610735482.31109.digitalmars-d@puremagic.com
More information about the Digitalmars-d
mailing list