shared_ptr 的动态转换 [英] dynamic cast of a shared_ptr
问题描述
我有几个类,其中我制作了 std::shared_ptr 版本,如下所示:
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
}
在内部,我将所有内容作为 MediaItemPtr 对象传递,但是当我尝试转换为 ImageMediaItemPtr 时,我尝试的任何内容似乎都不起作用.例如:
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
失败
错误 C2440:正在初始化":无法从'std::tr1::shared_ptr<_Ty>' 到 'std::tr1::shared_ptr<_Ty>'
error C2440: 'initializing' : cannot convert from 'std::tr1::shared_ptr<_Ty>' to 'std::tr1::shared_ptr<_Ty>'
对这个演员表应该如何实际工作有任何想法吗?我对 shared_ptr 有点陌生
Any thoughts of how this cast should actually work? I'm a bit new to shared_ptr
推荐答案
dynamic_pointer_cast
的模板参数应该是指向类型.换句话说,它应该是 T
而不是 shared_ptr
.
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>
.
在这种情况下,它应该是 dynamic_pointer_cast
而不是 dynamic_pointer_cast
.
In this case, it should be dynamic_pointer_cast<ImageMediaItem>
and not dynamic_pointer_cast<ImageMediaItemPtr>
.
这篇关于shared_ptr 的动态转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!