Dispatching on a variant

language_fan foo at bar.com.invalid
Sat Sep 26 07:20:25 PDT 2009


Sat, 26 Sep 2009 09:32:55 -0400, Justin Johansson thusly wrote:

> I've had a good poke around the forums and couldn't find anything on
> this so ...
> 
> What's the recommended method for dispatching code off the runtime type
> of a variant variable (Phobos D2 std.variant)?
> 
> Does one use a bunch of
> 
> if ( var.peek!(type1)) { ... }
> else if ( var.peek!(type2)  { ... }
> 
> for all N possible types, or is there a better & faster way with a
> switch or jump table of sorts?

If the type count gets large, how fast it is depends on the backend 
optimizations of the compiler. In the worst case it is a O(n) time linear 
search. A jump table or almost any other way of dispatching would be 
faster. If the variant had an integral tag field, it could be used in a 
switch; that way the compiler could easily optimize it further with the 
currently available constructs.

This problem is solved in higher level languages by providing pattern 
matching constructs. The compiler is free to optimize the code the way it 
likes:

  case var of
    type1 => ...
    type2 => ...
    ...

But since no C-like language has ever implemented pattern matching, it 
might be too radical to add it to D.



More information about the Digitalmars-d mailing list