Double-dispatch

Lutger Blijdestijn lutger.blijdestijn at gmail.com
Sun Feb 13 11:32:14 PST 2011


Sean Eskapp wrote:

> I remember in C++, I had to do double-dispatch using the visitor pattern.
> This is cumbersome, just because each subclass has to have the exact same
> singly-dispatched code that looks like:
> 
> void dispatch(Base& other)
> {
>    other.dispatch(*this);
> }
> 
> Is there a nicer way to do this in D, or am I stuck with the same thing?

There isn't really, but you can take out some of the boilerplate with a 
mixin, which goes a long way:

// The template parameter Visitor is not actually needed, depending on 
// what you want to do
mixin template Accept(Visitor)
{
    void accept(Visitor v)
    {
        v.visit(this);
    }
}

class Stuff
{
    mixin Accept!IStuffVisitor;
}



With some ctfe it's also not too hard to take out the boilerplate of 
creating the visitor interface with a bit of code generation, though I'm not 
sure if it's worth it.


More information about the Digitalmars-d-learn mailing list