dynamic cast of a shared_ptr

2019-05-10 05:46发布

问题:

I have a few classes of which I've made std::shared_ptr versions, as follows:

typedef std::shared_ptr<MediaItem> MediaItemPtr;
typedef std::shared_ptr<ImageMediaItem> ImageMediaItemPtr;

class MediaItem
{
   //stuff here
}

class ImageMediaItem : public MediaItem
{
   //more stuff here
}

Internally, I pass everything around as a MediaItemPtr object, but when I try to cast to a ImageMediaItemPtr, nothing I try seems to work. For example:

ImageMediaItemPtr item = std::dynamic_pointer_cast<ImageMediaItemPtr>(theItem);
//theItem is MediaItemPtr

Fails with

error C2440: 'initializing' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'std::tr1::shared_ptr<_Ty>'

Any thoughts of how this cast should actually work? I'm a bit new to shared_ptr

回答1:

The template argument to dynamic_pointer_cast should be the pointed-to type. In other words, it should be T and not shared_ptr<T>.

In this case, it should be dynamic_pointer_cast<ImageMediaItem> and not dynamic_pointer_cast<ImageMediaItemPtr>.



回答2:

Try:

ImageMediaItemPtr item = std::dynamic_pointer_cast<ImageMediaItem>(theItem);