Because we have ranges! 🙂
In my previous blog post, I gave a tutorial on the double dispatch pattern. I mentioned that you could reuse the pattern for a variety of things, one of those being I/O. In this blog post, we’ll walk through how we can add serialization support for our class hierarchy without touching the classes themselves.
Okay, you’ve ended up in a situation where you’re either
dynamic_cast* to find out the actual type of a pointer, then moving on to do what you really want, or
- checking some
enumin 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.
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++”