
hi, yesterday in the beer garden there was a discussion going on where i tried to explain the advantage of generic functions over the way that java or c++ implement their runtime type polymorphism on only one argument, the implicite 'this' argument. the example choosen to show the problems with only single method dispatching was the collission of two 2 dimensional shapes, e.g. triangle, circle, square, rectangle, ellipse, ... in java the 'best' way to achieve double dispatch is probably some variation of the visitor pattern, something along the lines: class Triangle implements Shape { public boolean collidesWith(Shape other) { other.collidesWithTriangle(this); } ...; public boolean collidesWithCircle(Circle s) {...;} public boolean collidesWithSquare(Square s) {...;} ...; } you avoid the if-then-elses, but if you add a shape later you will have to touch all sublasses of Shape and add the collidesWithNewShape method. because collission detection is symmetric, e.g. it does not matter if you say collidesWith(Triangle t, Circle c) or collidesWith(Circle c, Triangle t) it is not obvious if the actual code that does the collision detection between these two shapes should be in the Triangle or in the Circle class. probably it is best factored out in a third CollisionDetectionAlgorithm class which only contains static methods for each combination of shapes. as you can see you have to be already quite imaginative to implement double type dispatch and it will become even more complex with more than two types on which you would like to dispatch. you avoid the problem completely by using multimethods, e.g. CLOS in lisp or language extensions like NICE for java: http://nice.sourceforge.net/ i've also seen some time ago an extension to gcc that allows you to use multimethods in C++, but i cannot find it at the moment. there are two related documents that i found by quickly browsing through some google results: http://www.cs.technion.ac.il/~imaman/stuff/mm.ppt https://www.informit.com/content/images/0201704315/samplechapter/alexan11.pd... -- Christian Schuhegger http://www.el-chef.de/