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

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 15 07:24:05 PDT 2015


On 2015-07-14 17:53, Rene Zwanenburg wrote:

> Sure, but that would make Base!Derived and Base!AnotherSubClass
> different types.
>
> What I'd like to end up with is a Base[], being able to call foo() on
> the array members. Other parts of the code will add instances of derived
> types to this array, and have set the callback function to a delegate
> accepting said derived type.

You can add another base type that is not templated:

abstract class Base
{
     abstract void foo ();
}

abstract class TemplateBase(T) : Base
{
     alias CallbackType = void delegate(T);

     CallbackType callback;

     override void foo ()
     {
         callback(cast(T) this);
     }
}

class Derived : TemplateBase!(Derived)
{
     void derivedFunc()
     {
         import std.stdio;
         writeln("Derived object in action...");
     }
}

void main()
{
     auto d = new Derived();
     d.callback = (Derived d) { d.derivedFunc(); };
     Base[] bases = [d];
     foreach (b ; bases)
         b.foo();
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list