Q: How to return sub class from base class method
Myron Alexander
someone at somewhere.com
Mon Jun 18 02:13:50 PDT 2007
Jari-Matti Mäkelä wrote:
> 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 :)
Thanks all.
I am happy with the mixin solution, even if I forget to add the mixin,
the compiler will generate an error when I try to chain the class
methods after the doSomething so it's not a dangerous one at that.
Just for your information, I attached the test source where I am using
it. The doSomething method here is called 'initCause'.
Regards,
Myron.
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: exc.d
Url: http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070618/756c1690/attachment-0001.txt
More information about the Digitalmars-d-learn
mailing list