Is it possible to return the subclass from a method of the parent class in dlang?

Christian Köstlin christian.koestlin at gmail.com
Sat Mar 3 00:09:10 UTC 2018


On 02.03.18 21:39, Steven Schveighoffer wrote:
> On 3/2/18 3:23 PM, Christian Köstlin wrote:
>> To give an example:
>>
>> class Thread {
>>    ...
>>    Thread start() {...}
>> }
>>
>> class Timer : Thread {
>>    ...
>> }
>>
>>
>> void main() {
>>    // Timer timer = new Timer().start;  // this does not work
>>    auto timer = new Timer().start; // because timer is of type Thread
>> }
> 
> Yes:
> 
> class Timer : Thread {
>    override Timer start() { ... }
> }
> 
> https://dlang.org/spec/function.html#virtual-functions
> 
> (see item 6)
> 
> -Steve
Thanks for this.
It works for me only without the override (with override I get
Error: function timer.Timer.start does not override any function, did
you mean to override 'core.thread.Thread.start'?).

Although I wonder if its possible to "fix" this in the Thread class with
some dlang magic. e.g. traits
class Thread {
  traits(GetClass) start() {...}
}

or perhaps

class ThreadHelper(T) : Thread {
  override T start() {return cast(T)super.start();}
}
class Timer : Thread!Timer {
}


More information about the Digitalmars-d-learn mailing list