All the time, I find myself doing something like this:
Animal *animal = ...
if (Cat *cat = dynamic_cast(animal)) {
...
}
else if (Dog *dog =
template
void action_if(B* value, std::function action)
{
auto cast_value = dynamic_cast(value);
if (cast_value != nullptr)
{
action(cast_value);
}
}
Animal* animal = ...;
action_if(animal, [](Cat* cat)
{
...
});
action_if(animal, [](Dog* dog)
{
...
});
I don't have access to a C++11 compiler right this second to try this out, but I hope the idea is useful. Depending on how much type inference the compiler is capable of, you may or may not have to specify the case's type twice - I'm not C++11-pro enough to tell from looking at it.