On 3/5/22 14:46, Adam D Ruppe wrote:
Put a static constructor in the class which appends a factory delegate
to an array or something you can use later. Then you can use your own
thing to construct registered objects.
I'd like to do a runtime registration system myself, using a "template
this" static constructor. A simple version supporting only default
constructors would be:
```d
module test;
import std.stdio : writeln;
class MyObject {
/* static */ this(this T)() {
string type = typeid(T).name;
if (type !in generators) {
generators[type] = () => new T();
}
}
static MyObject factory(string type) {
if(type in generators) {
return generators[type]();
} else {
return null;
}
}
private:
static MyObject function()[string] generators;
}
class MyClass : MyObject {
this() {
writeln("Creating MyClass");
}
}
void main() {
auto _ = new MyClass(); // Shouldn't be needed
auto myClass = MyObject.factory("test.MyClass");
}
```
Unfortunately, this isn't currently possible:
https://issues.dlang.org/show_bug.cgi?id=10488
https://issues.dlang.org/show_bug.cgi?id=20277
(notice the big number of duplicates).
The closest feasible option is to put it in a non-static constructor,
and that's suboptimal: it forces an instantiation of the class, and it
will be run at every instantiation.
Alternatively, instruct the users to create a static constructor for
each of the classes they'd like registered (perhaps through a mixin),
but that's also quite cumbersome.