Idea: Lazy upcasting
Reiner Pope
some at address.com
Tue Mar 27 14:57:16 PDT 2007
Marcin Kuszczak wrote:
> Hello!
>
> Recently I have tried to achieve chaining a few calls to setters. I mean
> something like below:
>
> //-------------------------------------------
>
> abstract class Storage {
> Storage param1(int p1) {
> this.p1 = p1;
> return this;
> }
> private:
> int p1;
> }
>
> class SpecificStorage : Storage {
> public:
> SpecificStorage param2(bool p2) {
> this.p2=p2;
> return this;
> }
> private:
> bool p2;
> }
>
> void main() {
> // ...ok... ...ok... ...ups!
> SpecificStorage1 s1 = (new SpecificStorage).param2(true).param1(5);
> }
>
> //-------------------------------------------
How about:
interface Storage
{
Storage param1(int);
}
abstract class StorageImpl(T) : Storage {
static assert(is(typeof(this) == T));
T param1(int p1)
{
this.p1 = p1;
return cast(T)this;
}
private int p1;
}
class SpecificStorage : StorageImpl!(SpecificStorage) {
SpecificStorage param2(bool p2) {
this.p2 = p2;
return this;
}
private bool p2;
}
That should already work.
Cheers,
Reiner
More information about the Digitalmars-d
mailing list