Q: How to return sub class from base class method

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


Myron Alexander wrote:

> I have a class structure as such:
> 
>> class A {
>>    typeof(this) doSomething (????) {
>>       ...
>>       return this;
>>    }
>> }
>> 
>> class B : A {
>>    typeof(this) doSomethingElse (????) {
>>       ...
>>       return this;
>>    }
>> }
>> 
>> void main () {
>>    // Fails
>>    B b = (new B()).doSomething (???).doSomethingElse (???);
>> }
> 
> The method chain fails as doSomething returns type A.
> 
> I want to define method doSomething in such a way that it will return
> the specialized type (B) rather than the base type.
> 
> Is there a way to set the return type as the type instantiated?

Yes, you can use CRTP
(http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern).

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.


More information about the Digitalmars-d-learn mailing list