A lightweight module for class extensions in D

Gregor Richards Richards at codu.org
Fri Dec 5 08:37:57 PST 2008


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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: extensions.d
Type: text/x-dsrc
Size: 3019 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20081205/adc29bd6/attachment.d>


More information about the Digitalmars-d mailing list