Idea: A library non-OOP "dispatch!()()"

Nick Sabalausky a at a.a
Sun Mar 11 01:48:20 PST 2012


Maybe it's just half-asleep crazy-talk, but you know what I think would be 
great in Phobos (I don't *think* it's already there)? A virtual-like 
"dispatch" function, which would help ease the rift between template code 
and OOP. For example, if you have a class hierarchy, you can do 
single-dispatch via method overriding. But if you have a function implemeted 
outside the class that uses overloading on type, you have to dispatch 
manually:

class FooBase {}
class Foo1 : FooBase  {}
class Foo2 : FooBase  {}
class Foo3 : FooBase  {}

void bar(FooBase f)
{
    if(auto _f = cast(Foo1)f)
        bar(_f);
    else if(auto _f = cast(Foo1)f)
        bar(_f);
    else if(auto _f = cast(Foo2)f)
        bar(_f);
    else
        throw new Exception("Can't dispatch");
}
void bar(T f) if(is(T : FooBase))
{
    // use 'f'
}

Thats a lot of boilerplate!

I'm finding I need to do that sort of thing a lot when using my Goldie lib.

It could be improved with a foreach over a TypeTuple, but it'd be great to 
have a "dispatch!()()" or even a multiple dispatch version to just automate 
all of that entirely. That would grant D the feature of multidispatch and 
non-OOP dispatch *in library*, and really help ease the rift between OOP and 
non-OOP styles of coding.

Or, the same thing but without a class hierarchy. For example, if you have 
ten different ForwardRange types you want to deal with.

My half-asleep self thinks that that *should* probably be possible to 
create. The real trick I think would be in figuring out the 
interface/semantics for controlling what types to actually try to dispatch 
on.





More information about the Digitalmars-d mailing list