On 07/14/2015 08:28 AM, Rene Zwanenburg wrote: > But the CallbackType should be able to prevent such unsafe assignments.
The following struct applies what others have recommended only if an actual derived type is provided. However, it is still unsafe as the direct assignment to 'callback' cannot know that the object is the same as template parameter D.
struct CallbackBased(B) { alias Func = void delegate(B); Func func; void opAssign(D)(void delegate(D) arg) if (is (D : B)) { func = cast(Func)(arg); } void opCall(B obj) { func(obj); } } class Base { alias CallbackType = CallbackBased!Base; CallbackType callback; void foo() { callback(this); } } class Derived : Base { void derivedFunc() { import std.stdio; writeln("Derived object in action..."); } } void main() { auto d = new Derived(); d.callback = (Derived d) { d.derivedFunc(); }; d.foo(); } Ali