Q: How to return sub class from base class method

Jari-Matti Mäkelä jmjmak at utu.fi.invalid
Sun Jun 17 20:18:44 PDT 2007


Kirk McDonald wrote:

> Jari-Matti Mäkelä wrote:
>> class A(T) {
>>   T doSomething() {
>>     ...
>>     return cast(T)this;
>>   }
>> }
>> 
>> class B(T) : A!(T) {
>>   T doSomethingElse() {
>>     ...
>>     return cast(T)this;
>>   }
>> }
>> 
>> There might be other (more clever) ways to do this too. Like a mixin for
>> the "selftype" or something.
> 
> I believe B should look like this, if you're using that pattern:
> 
> class B : A!(B) {
>    B doSomethingElse() {
>      // ...
>      return this;
>    }
> }

Actually no - class B was supposed to be in the middle of the hierarchy so
class C would have looked like that :)

Something like

class A(T = A) { ... }
class B(T = B) : A!(T) { ... }

would have been nice for those non-abstract base classes so they could have
been instantiated too, but apparently the compiler didn't want to
co-operate this time.

> 
> Thus, B is derived from a class template to which you pass B as a
> parameter. This is often used in C++ as a way of emulating mixin-like
> behavior. Thus, D's template mixins could very well be a better solution.
> 

Feel free to create a better solution :)


More information about the Digitalmars-d-learn mailing list