Automatic return type covariance for functions that return this?

Andrej Mitrovic andrej.mitrovich at gmail.com
Sat Sep 15 15:06:26 PDT 2012


On 9/15/12, Ben Davis <entheh at cantab.net> wrote:
> The last line doesn't compile because doStuff() returns Super. Is there
> a way to make it return Sub without having to explicitly override the
> function?

You need a dynamic cast at the call site:

Sub x = cast(Sub)(new Sub()).doStuff();

x will be null if doStuff doesn't actually return a Sub object
(replace 'new Sub' with 'new Super' for demonstration).

You can't guarantee that the 'this' reference returned in the base
class doStuff method will be of dynamic type 'Sub', that's why
implicit conversions don't work. Either define this method in every
subclass or use casts at the call site.

Maybe you're looking for automatic injection of code into every
subclass, but I don't think this is possible in D. Using mixins might
work, but you'd still have to instantiate a mixin in every subclass by
hand.


More information about the Digitalmars-d-learn mailing list