Covariant callback functions, or assigning base class members through a subclass reference

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 14 10:26:35 PDT 2015


On 7/14/15 11:28 AM, Rene Zwanenburg wrote:
> Given the following code:
>
> class Base
> {
>      alias CallbackType = void delegate(Base);
>
>      CallbackType callback;
>
>      void foo()
>      {
>          callback(this);
>      }
> }
>
> class Derived : Base
> {
>
> }
>
> void main()
> {
>      auto d = new Derived();
>      d.callback = (Derived d) { /* Do something */ }
> }
>
> Obviously this won't compile, since the callback function needs to have
> Base as parameter, not Derived. But the given code is perfectly safe
> because in main d typed as Derived, not Base. Does anyone know a clean
> way to support the code given in main(), preferably by defining some
> smart CallbackType so Derived doesn't need to be modified?

No, this isn't possible. Only thing you can do is:

d.callback = (Base b) { if(auto d = cast(Derived)b) { /* Do something */ 
} else assert(0); };

-Steve


More information about the Digitalmars-d-learn mailing list