Dispatching values to handlers, as in std.concurrency

Idan Arye GenericNPC at gmail.com
Mon May 6 14:20:48 PDT 2013


On Monday, 6 May 2013 at 17:03:20 UTC, Luís Marques wrote:
> I have a list of functions which receive values of different 
> types, like in std.concurrency...
>
>     // example from std.concurrency
>     receive(
>          (int i) { writeln("Received the number ", i);}
>      );
>
> ...although in my case I can probably live by with only 
> accepting objects.
>
> I built a list of the handlers and the message classes they 
> accept. My problem is that I don't know how to check if the 
> message I have to dispatch is of the class the handler accepts 
> *or a subclass*. I only managed to check for class equality:
>
>     if(typeid(msg) == typeHandler.type)
>     {
>         typeHandler.handler(msg);
>     }
>
> How can I also accept subclasses?
>
> Thanks,
> Luís

Just cast it - http://dlang.org/expression.html#CastExpression
Casting object `foo` to type `Bar` will yield `null` if `foo` is 
not an instance of a `Bar` or of a subclass of `Bar`.

This is particularly usefull combined with a declaration inside 
an `if` statement:

     if(auto castedObject = cast(typeHandler.type)msg)
     {
         typeHandler.handler(msg);
     }

BTW, for this to work `typeHandler.type` needs to be known at 
compile-time.


More information about the Digitalmars-d-learn mailing list