Templates for instantiating derived class

Steven Schveighoffer schveiguy at gmail.com
Tue Sep 21 01:07:12 UTC 2021


On 9/20/21 6:16 PM, rjkilpatrick wrote:
> 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.
> 

...

> 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.

What you want is to change that operator into a virtual function. Yes, 
you still have to write the overrides, but you could if you want use a 
mixin. Adam's solution works, but only uses the static type.

```d
class Super {
     private int _a;
     this(){}
     this(int a) {
         _a = a;
     }

     Super performAdd(int rhs) const {
         return new Super(_a + rhs);
     }

     alias opBinary(string op : "+") = performAdd;
}

class Derived : Super {
     this(){}
     this(int a) {
         _a = a + 1;
     }

     override Derived performAdd(int rhs) {
         return new Derived(_a + rhs);
     }
}

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; // works now

     Super b2 = bar;
     Derived d2 = cast(Derived)(b2 + 1); // ok, *and* calls Derive's 
version of performAdd
     assert(d2 !is null && d2._a == bar2._a);
}
```


More information about the Digitalmars-d-learn mailing list