Double dispatch without RTTI
I liked my StackOverflow answer so much that I decided to make it into a blog post. The question was how to implement a double dispatch mechanism for subclasses of one base class without casting. After dismissing the question as stupid, I spent a bit of time trying to come up with a solution that didn’t rely on
dynamic_cast. The solution is pretty pointless as it’s pretty confusing and might be slower than RTTI solution due to an extra function call. It was largely inspired by wikipedia article on double dispatch found here.
So the trick to get this working as pointed out in the article was to call the function on the pointer or reference of the parameter to the original function, thus cauising a second dispatch.
The problem with doing this sort of thing with subclasses of the same base is that we need to allow the possibility of the base class being called with one of its subclasses as a parameter. Luckily we can use forward declarations to define the functions and implement them later on.
The code is far from an ideal double dispatch solution as it relies on the forward declaration trick to resolve the circular dependency between the subclasses. This means that all the classes that need to have this functionality must be known at compile-time (of the base class). This means the base class cannot be made into a library component.
To explain all the friend declarations. Considering the fact that all the classes
c are tightly coupled as is, I added friend declarations so that the actual worker function is private and cannot be called from the outside.
blog comments powered by Disqus