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?
I understand this is unsafe in other scenarios, for example:
class AnotherSubClass : Base
{
}
void bar(Base b1, Base b2)
{
b1.callback = b2.callback;
}
void doom()
{
auto b1 = new Derived();
auto b2 = new AnotherSubClass();
b2.callback = (AnotherSubClass a) { };
bar(b1, b2);
}
But the CallbackType should be able to prevent such unsafe
assignments.