Covariant callback functions, or assigning base class members through a subclass reference
Rene Zwanenburg via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 14 10:58:58 PDT 2015
On Tuesday, 14 July 2015 at 17:26:32 UTC, Steven Schveighoffer
wrote:
> 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
Thanks, I'll have to think of something else then.
At my day job I mostly work with C#, and I strongly dislike how
event handler parameters there have to be broader-typed (is that
even a valid term?) than they logically need to be, which is why
I'm trying to avoid doing something similar here.
More information about the Digitalmars-d-learn
mailing list