Overloading free functions & run-time dispatch based on parameter types

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 6 06:33:57 PST 2016


On Friday, 5 February 2016 at 19:48:45 UTC, Robert M. Münch wrote:
> I thought about it too, but I need it to work with more then 
> one parameter, so I tried this which doesn't work:
>
> Value nativePlus(Value a, Value b){
>  // @@ not working, runtime exception
>  castSwitch!(
>      (IntV a) {
>        castSwitch!(
>            (IntV b) {return new IntV(a.num + b.num);}
>        )(b);
>      },
>
>      (StringV a) {return new StringV("string plus");},
>  )(a);
>
>  // to keep compiler happy when using castSwitch (has no return 
> statement)
>  return new UnsetV();
> }
>

I don't see why this wouldn't work, if you've in fact covered all 
combinations. One thing that tripped my up was a null references 
- these are never castable to anything, not even Object. If not 
all combinations are valid, you can add a lambda that accept 
Value (or even Object), which is called as a "default" branch.

>
> and ended with this, which works and is straight forward but 
> maybe not that elegant:
>
> Value nativePlus(Value a, Value b){
>
>  if(cast(IntV) a && cast(IntV) b)
>    return new IntV((cast(IntV)a).num + (cast(IntV)b).num);
>
>  if(cast(StringV) a && cast(StringV) b)
>    return new StringV((cast(StringV)a).str ~ 
> (cast(StringV)b).str);
>
>  // if no case was hit (could throw)
>  return new UnsetV();
> }
>
> Can this be written simpler or more elegant?

It's similar to how castSwitch is implemented, though the double 
casts are inefficient. You could use:

if(auto inta = cast(IntV) a) {
     if(auto intb = cast(IntV) b) {
         return new IntV(inta.num + intb.num);
     }
}

(Again, this can be automated.)

>
> I read this here: 
> https://github.com/D-Programming-Language/phobos/pull/1266#issuecomment-53507509 (functional pattern matching) but it seems it won't be implemented... at the end of the day what I simulate are poor-mans-multimethods

As I read the discussion, it was just decided to defer the more 
complex version of castSwitch for later, but it wasn't rejected.


More information about the Digitalmars-d-learn mailing list