Stop reimplementing the virtual table and start using double dispatch

Okay, you’ve ended up in a situation where you’re either

  1. using dynamic_cast* to find out the actual type of a pointer, then moving on to do what you really want, or
  2. checking some enum in a base class to see which derived class it really is so that you can perform type-specific operations on it

* or some other form of run-time type information

You know something is wrong with this, but you can’t think of a satisfactory solution. You’ve already considered adding another virtual function on the base class, but you’re worried about how many virtual functions are already there, or the impact that this might have on consumers of the base class.

Good on you for recognizing that. Admitting you have a problem is the first step to solving it 🙂

In this tutorial, I’ll talk about one solution to this problem I’ve had some success with: the double-dispatch Visitor pattern. With it, you can trim down those long if-else if blocks, separate responsibility into manageable pieces, and even stabilize your interface better.

Continue reading “Stop reimplementing the virtual table and start using double dispatch”

A true heterogeneous container in C++


Oftentimes I see questions StackOverflow asking something to the effect of

“Can I have a std::vector that holds more than one type?”

The canonical, final, never-going-to-change answer to this question is a thorough


C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.


Of course there are ways to work around this. You can hide types within types! In this post I will discuss the existing popular workarounds to the problem, as well as describe my own radical new heterogeneous container that has a much simpler interface from a client’s perspective. Continue reading “A true heterogeneous container in C++”