I have a question that remains after studying this example: C++ ecosystem simulator (inheritance).
Imagine that I have a similar example, where I want to work with the std::unique_ptr
. Is there a way to do the dynamic casting in the example below, without having to resort to getting the raw pointer using the .get()
on the std::unique_ptr
? I have put two variants in the code: one (can_eat_1
) that does it the old-fashioned way and one where I have a .get()
in the dynamic_cast
for which I wonder if it can be removed and replaced by a more elegant method (can_eat_2
):
#include <iostream>
#include <memory>
struct Animal
{
virtual ~Animal() {};
};
struct Carnivore : public Animal {};
struct Herbivore : public Animal {};
struct Wolf : public Carnivore {};
struct Rabbit : public Herbivore {};
bool can_eat_1(Animal* predator, Animal* prey)
{
return ( dynamic_cast<Carnivore*>(predator) && dynamic_cast<Herbivore*>(prey) );
}
bool can_eat_2(std::unique_ptr<Animal>& predator, std::unique_ptr<Animal>& prey)
{
return ( dynamic_cast<Carnivore*>(predator.get()) && dynamic_cast<Herbivore*>(prey.get()) );
}
int main()
{
std::unique_ptr<Animal> wolf (new Wolf );
std::unique_ptr<Animal> rabbit(new Rabbit);
std::cout << "Option 1: pass raw pointers:" << std::endl;
std::cout << "Wolf eats rabbit = " << can_eat_1(wolf.get(), rabbit.get()) << std::endl;
std::cout << "Rabbit eats wolf = " << can_eat_1(rabbit.get(), wolf.get()) << std::endl;
std::cout << "Option 2: pass unique_ptr:" << std::endl;
std::cout << "Wolf eats rabbit = " << can_eat_2(wolf, rabbit) << std::endl;
std::cout << "Rabbit eats wolf = " << can_eat_2(rabbit, wolf) << std::endl;
return 0;
}