All the time, I find myself doing something like this:
Animal *animal = ...
if (Cat *cat = dynamic_cast(animal)) {
...
}
else if (Dog *dog =
Some time ago I was experimenting to write a library for doing exactly that.
You can find it here:
https://github.com/nicola-gigante/typeswitch
The project was quite ambitious, with a lot of planned features, and it still needs to be finished (there's also an important bug that I already know, but I don't have time to work on it anymore in this months). However, for your use case of a classic hierarchy of classes, it would work perfectly (I think).
The basic mechanism is the same as you have posted before, but I try to extend the concept with more features:
T is the common type of the types returned by all the clauses. If there's no default case, the return type is optional instead of T.boost::optional or any implementation of std::experimental::optional from the current draft of the Library Foundamentals TS (for example, libc++ provides one).boost::any object.dynamic_cast. This is useful when using libraries that provide their own casting infrastructure, like Qt's qobject_cast, or to implement the typeswitch on your own tagged unions or anything like that.The library is quite finished, except for a bug that is documented in the README that makes impossible to match non-polymorphic types with static overloading resolution rules, but it's a case that would only be useful in templated generic code, and is not involved in the majority of use cases like yours. I currently don't have time to work on it to fix the bug, but I suppose it's better to post it here than leave it unused.