Design and evaluation of C++ open multi-methods

Peter Pirkelbauer, Yuriy Solodkyy, Bjarne Stroustrup
2010 Science of Computer Programming  
Multiple dispatch -the selection of a function to be invoked based on the dynamic type of two or more arguments -is a solution to several classical problems in object-oriented programming. Open multi-methods generalize multiple dispatch towards open-class extensions, which improve separation of concerns and provisions for retroactive design. We present the rationale, design, implementation, performance, programming guidelines, and experiences of working with a language feature, called open
more » ... -methods, for C++. Our open multi-methods support both repeated and virtual inheritance. Our call resolution rules generalize both virtual function dispatch and overload resolution semantics. After using all information from argument types, these rules can resolve further ambiguities by using covariant return types. Care was taken to integrate open multi-methods with existing C++ language features and rules. We describe a model implementation and compare its performance and space requirements to existing open multi-method extensions and workaround techniques for C++. Compared to these techniques, our approach is simpler to use, catches more user mistakes, and resolves more ambiguities through link-time analysis, is comparable in memory usage, and runs significantly faster. In particular, the runtime cost of calling an open multi-method is constant and less than the cost of a double dispatch (two virtual function calls). Finally, we provide a sketch of a design for open multi-methods in the presence of dynamic loading and linking of libraries. An intersect operation is a classical example of multi-method usage [51, Section 13.8]. For a hierarchy of shapes, intersect() decides if two shapes intersect. Handling all different combinations of shapes (including those added later by library users) can be quite a challenge. Worse, a programmer needs specific knowledge of a pair of shapes to use the most specific and efficient algorithm. Using the multi-method syntax from [51, Section 13.8], with virtual indicating runtime dispatch, we can write: bool intersect ( virtual const Shape&, virtual const Shape& ); // open−method bool intersect ( virtual const Rectangle&, virtual const Circle& ); // overrider We note that for some shapes, such as rectangles and lines, the cost of double dispatch can exceed the cost of the intersect algorithm itself.
doi:10.1016/j.scico.2009.06.002 fatcat:4xiiblj5xndtrk3sc24oavxxny