ReturnThis/@chain

Tomek Sowiński just at ask.me
Sat Jul 24 03:52:51 PDT 2010


Dnia 24-07-2010 o 04:21:57 dsimcha <dsimcha at yahoo.com> napisał(a):

> I'm working on the next iteration of my Plot2Kill library, and I  
> **really**
> have fallen in love with property chaining.  It's the greatest thing  
> since
> sliced arrays.  However, I've run into an issue that I had previously  
> overlooked:
>
> class Foo {
>     Type _val;
>
>     typeof(this) val(Type newVal) {
>         _val = newVal;
>         return this;
>     }
> }
>
> class Bar : Foo {
>     // More properties.
> }
>
> void main() {
>     auto bar = new Bar;
>     bar.val(someValue).barProperty(someOtherValue);  // Won't work.
> }
>
> Given that D2 is mostly finalized, it may be a little late for this, but  
> would
> it be feasible, at least far down the road, to add something like an  
> @chain
> annotation, which would only allow a member function to return this and  
> would
> implicitly downcast it to the subtype that was passed in as the this  
> pointer?
>  For example, assume we attached @chain to Foo.val():
>
> pragma(msg, typeof(bar.val(someValue)));  // Bar, not Foo.

This looks like a job for the template this parameter:

     T val(this T)(int newVal) {
         _val = newVal;
         return cast(T) this;
     }

Funny enough, if you put Bar into Foo (Foo bar = new Bar; ) it doesn't  
work no more.

Tomek


More information about the Digitalmars-d mailing list