multiple dispatch using run & compile time reflection

Christian Kamm kamm.incasoftware at shift-at-left-and-remove-this.de
Tue Jul 24 06:25:36 PDT 2007


I was experimenting with the new __traits and used it to create a
RTTI-dispatched visitor here:
http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D.announce&artnum=9348

I've extended the code to allow multiple dispatch and be a bit more generic.
The code is attached, an example is inline:

----
import multipledispatch, std.stdio;

class A {}
class B : A {}

class Foo
{
  void bar(A a1, A a2)
  { writefln("AA"); }

  void bar(A a, B b)
  { writefln("AB"); }
  
  void bar(B a, B b)
  { writefln("BB"); }

  // generates void dispatch(Object,Object)
  // that uses RTTI to call one of the overloads
  // defined above
  mixin MultipleDispatch!("bar", _0, _1);
}

void main()
{
  A a = new A;
  A b = new B;

  auto foo = new Foo;

  foo.dispatch(a, a); // writes AA
  foo.dispatch(a, b); // writes AB
  foo.dispatch(b, b); // writes BB
  
  foo.dispatch(b, a); // throws error
}
----

I have also included a MultipleDispatchFallthrough template that'll call the
best match instead of throwing an error if there's no exact match. However,
the implementation is pretty inefficient. (feel free to optimize)

Here are some rough benchmarks, relative to a virtual function call:

virtual function call: 1
MultipleDispatch with one DispatchArg: 2.5
MultipleDispatch with three DispatchArgs: 2.9
MultipleDispatch with one DispatchArg and Fallthrough: 10

As you can see, a call through MultipleDispatch will take roughly three
times as long as a virtual function call. Since a call to dispatch will
contain two virtual function calls, that's almost optimal.

Regards,
Christian
-------------- next part --------------
A non-text attachment was scrubbed...
Name: multipledispatch.d
Type: text/x-c++src
Size: 6882 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20070724/87c624a6/attachment.c>


More information about the Digitalmars-d mailing list