Search code examples
c++oopvirtual-functionsmultiple-dispatch

Virtual functions with two operands that can take many different types


Let me start with a concrete example. In C++, I have a hierarchy of classes under the abstract base class CollisionVolume. Any collision volume needs to be able to detectCollision with any other volume. This collision code is specialized based on the two subclasses in presence, but it is commutative: detectCollision(a, b) == detectCollision(b, a).

I need to use a mechanism similar to virtual functions since the objects will typically be of the abstract base class. However, if I use typical virtual methods, the chosen function can only depend on the type of one of the operand, not both. The only way I was able to do this is using RTTI or an RTTI-like mechanism.

Is there any cleaner way to do this?


Solution

  • You're looking for multiple dispatch. C++ doesn't have it because it's hard to implement efficiently. Most other statically typed/efficiency-oriented languages don't either. Your RTTI solution is probably about the best way of faking it.