dynamic cast of a shared_ptr

2019-05-10 05:59发布

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

2条回答
叼着烟拽天下
2楼-- · 2019-05-10 06:34

Try:

ImageMediaItemPtr item = std::dynamic_pointer_cast<ImageMediaItem>(theItem);
查看更多
你好瞎i
3楼-- · 2019-05-10 06:39

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>.

查看更多
登录 后发表回答