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

Robert M. Münch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 5 11:48:45 PST 2016


On 2016-02-05 15:23:53 +0000, Marc Schütz said:

> Does the following help?
> ...

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();
}


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?

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

-- 
Robert M. Münch
http://www.saphirion.com
smarter | better | faster



More information about the Digitalmars-d-learn mailing list