dynamic cast of a shared_ptr

混江龙づ霸主 提交于 2019-12-07 17:42:15

问题


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);


来源:https://stackoverflow.com/questions/20219385/dynamic-cast-of-a-shared-ptr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!