3

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

0

2 Answers 2

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

godbolt.org/g/IQHPOL I'm trying your solution and it doesn't seem to work. What am I missing here?
@arunmoezhi As the error message says, "the operand of a runtime dynamic_cast must have a polymorphic class type", i.e. your class needs to have a virtual function.
6

Try:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.