A lightweight module for class extensions in D

Christopher Wright dhasenan at gmail.com
Fri Dec 5 19:33:52 PST 2008


Gregor Richards wrote:
> 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).

I usually use this pattern but make it more explicit, using interfaces 
and direct casting in client code. I'm not sure I want to use this, 
given that it does use string mixins.

You could define the "extension" method more like:
char[] textension(char[] funcname, TTarget, TReturn, TArgs...)()
{
    return extension (TTarget.stringof, TReturn.stringof, funcname, 
GetTypedArgString!(TArgs), GetUntypedArgString!(TArgs));
}

And extend:
template extend(char[] funcname, alias func)
{
    static this ()
    {
       mixin (`__ext_` ~ funcname ~ 
`[ParameterTupleOf!(func)[0].classinfo] = cast(void*) &func;`);
    }
}



More information about the Digitalmars-d mailing list