Essentially, I would like to write a template that calls the constructor of the parent class or the constructor of the inherited class, depending on its type.
#!/usr/bin/env dub
/+ dub.sdl:
name "mwe"
+/
class Super {
private int _a;
this(){}
this(int a) {
_a = a;
}
auto opBinary(string op)(int rhs) const if (op == "+") {
return new Super(_a + rhs); // Creates of type Super even when called from derived class
}
}
class Derived : Super {
this(){}
this(int a) {
_a = a + 1;
}
}
void main() {
import std : writeln;
Super foo = new Super(1);
Super foo2 = foo + 1; // Works fine as calls `Super` constructor
Derived bar = new Derived(2);
Derived bar2 = bar + 1; // Cannot implicitly cast `Super` to `Derived`
}
Some kind of return new this(...)
would be good, but that's not possible.
I think it has to be done with templates, but I'm not sure how to do this.
Any help would be greatly appreciated.