I have problems with this. Let them say that I have this vector
std::vector<std::shared_ptr<Car>> cars;
The car is an abstract class. I want to be able to return weak pointers of different types, so I do the following.
template<typename T> std::weak_ptr<T> GetCar() { for (std::vector<std::shared_ptr<Car>>::iterator it = cars.begin(); it != cars.end(); ++it) { T* derived = dynamic_cast<T*>((*it).get()); if (derived != nullptr) { std::weak_ptr<T> carPointer = *it; return carPointer; } } return std::weak_ptr<T>(); }
I get the following error though when I try to use a function with a class that inherits from Car. Error C2440 'initializing': cannot convert from 'std::shared_ptr<Car>' to 'std::weak_ptr<Saab>' When asked, there cannot be a valid car. I tried using boost :: optional, but it does not handle polymorphism. I can go with rude pointers if I can't get this to work.
source share