A lightweight module for class extensions in D

Nick Sabalausky a at a.a
Sat Dec 6 15:24:48 PST 2008


"Gregor Richards" <Richards at codu.org> wrote in message 
news:ghbld5$23j7$1 at digitalmars.com...
>I ran into a situation where I needed (essentially) the visitor pattern, 
>but the visitor pattern sucks, so I wanted to make something like class 
>extensions instead (that is, methods added to a class outside of the class 
>definition).
>
> Of course, it's not possible to do this particularly cleanly, but I made a 
> system that works (albeit using gross string mixins). Essentially, if you 
> have a class A, class B : A, class C : B, you could do something like 
> this:
>
> mixin(extensions("A", "void", "doFoo", "", ""));
>
> mixin(extend("A", "doFoo"));
> void A_doFoo(A pthis) {
>    /* method for A */
> }
>
> mixin(extend("B", "doFoo"));
> void B_doFoo(B pthis) {
>    /* method for B */
> }
>
> Then if you call doFoo(new A()) the call will become A_doFoo(new A()), if 
> you call doFoo(new B()) the call will become B_doFoo(new B()), if you call 
> doFoo(new C()) the call will become B_doFoo(new C()).
>
> If anybody has some improvements, that'd be cool. Maybe you can get rid of 
> the dependence on string mixins ... but I don't think templates quite cut 
> it.
>
> - Gregor Richards
>

Congrats for getting an extension-like feature into D through a simple lib. 
But I hope nobody (*cough* Walter) mistakes this as a sufficient substitute 
for real extension methods (*hint* *hint*) ;) 





More information about the Digitalmars-d mailing list