Been experimenting and searching for how to do this and would like some help....
Goal : Have a std::vector store either Cat and Bear objects (like a heterogenous container). Then iterate the vector and perform an overloaded function A or function B depending on type (Cat/Bear)
Solution : I created a base class (Animal), the std::vector stores shared_ptrs of this type.
I create Animal derived Cat or Bear objects (new), cast their pointers to shared_ptr<Animal> and push to vector.
Problem : I have two processing functions that take Cat or Bear parameters respectively. But I need to std::static_pointer_cast<Bear> or std::static_pointer_cast<Cat> the Animal pointers from the vector before passing to the function. I want the correct function to be called automatically (due to overloading).
thanks
class AnimalClass
{
AnimalType type;
};
class Bear : public AnimalClass
{
}
class Cat : public AnimalClass
{
}
void action(Bear* bear)
{
run();
}
void action(Cat* cat)
{
stroke();
}
int main()
{
std::vector<shared_ptr<AnimalClass>> store;
// Populate store
Cat* cat= new Cat();
store.push_back(shared_ptr<AnimalClass>)cat );
Bear* bear= new Bear();
store.push_back(shared_ptr<AnimalClass>)bear );
// Process store
for (auto item : store)
{
action(item); // Does not compile unless item is static_pointer_cast to Bear or Cat, don't want to do that.
}
}