Dispatching values to handlers, as in std.concurrency

Idan Arye GenericNPC at gmail.com
Mon May 6 23:19:23 PDT 2013


On Tuesday, 7 May 2013 at 00:15:06 UTC, Luís Marques wrote:
> On Monday, 6 May 2013 at 23:53:51 UTC, Idan Arye wrote:
>> If the type handlers are your own classes, then you can let 
>> them check it. Have a method in the handlers that check if an 
>> object can be handled by that handler, and use it on each 
>> handler until you find one that fits.
>
> I don't understand. Imagine I have:
>
>     class X
>     {
>         void handleFoo(Foo msg) { ... }
>
>         void handleBar(Bar msg) { ... }
>     }
>
> I want to register an instance of X to receive messages of type 
> Foo (or subclass) and messages of type Bar (or subclass) in the 
> respective handler methods. Where are you proposing for your 
> check to be implemented?

I assume that `typeHandler` in your original code is *not* of 
type `X` - since it has a single `handler` method while `X` has 
two, with different names. That means that at some point, you had 
to create it - let's assume it's type is called `TypeHandler`. 
There is either a global function, static method, or constructor 
where you create a `TypeHandler` and pass to it the delegate you 
want to register.

Now, if that function/method/constructor is templated - than you 
already have at compile time the type you want to handle, so you 
can prepare the check there(anon function?)

If it's not templated - make it templated! You don't have to make 
the entire `TypeHanler` templated, just the method that creates 
it. There, you can create an anonymous function that receives 
`Object` and returns `bool` and all it does is check for type, 
and you can have a field in `TypeHandler` that keeps that 
function and uses it to check if it can handle a certain type.


More information about the Digitalmars-d-learn mailing list