Idea: A library non-OOP "dispatch!()()"
Timon Gehr
timon.gehr at gmx.ch
Sun Mar 11 04:43:04 PDT 2012
On 03/11/2012 10:48 AM, Nick Sabalausky wrote:
> 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.
Yes, it is.
> The real trick I think would be in figuring out the
> interface/
A overloadSet(A a){ ... }
B overloadSet(B b){ ... }
C overloadSet(B b, C c){ ... }
...
auto dispatch!overloadSet(args...)
The return type would just be the common type of all overload set return
types.
> semantics
The main issue is how to deal with ambiguities and non-existence of a
suitable method.
> for controlling what types to actually try to dispatch on.
>
>
>
More information about the Digitalmars-d
mailing list