Q: How to return sub class from base class method

Kirk McDonald kirklin.mcdonald at gmail.com
Sun Jun 17 19:37:08 PDT 2007


Jari-Matti Mäkelä wrote:
> 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.

I believe B should look like this, if you're using that pattern:

class B : A!(B) {
   B doSomethingElse() {
     // ...
     return this;
   }
}

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.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list