Smart Pointer Casting ( Base to Derived<T> )
-
Can someone explain the following to me ? :
class Base { fn_base(){...}; }; template < class T > class Derived : public Base { fn_derived(){...}; T value_; };I have 2 classes as you can see above.
Additionally I have a map that cointains shared_ptr<Base> + a specific id.std::map< const std::string id, std::shared_ptr<Base>> objects_;Now I want to store an object of type Derived<T> in the map ( works fine ) and receive the value of it somewhere else ( here is the problem )
template < class T > T getObjectValue( const std::string id ){ if ( object_.find(id) != objects_end()){ return std::dynamic_pointer_cast<Derived<T>>(objects_.at(id))->getValue(); } }This :
return std::dynamic_pointer_cast<Derived<T>>(objects_.at(id))->getValue();Doesn't work. But when I replace T with a specified type it works ?
return std::dynamic_pointer_cast<Derived<int>>(objects_.at(id))->getValue();Can someone explain that ? And if you can, would you mind giving me a hint on how I can work around that ?
-
Now I want to store an object of type Derived<T> in the map ( works fine )[...]
I meant a std::shared_ptr<Derived<T>>
-
Why is your signature in German but the post in English?
Please show us a reproducible example, don't merely paste extracts that don't even compile.
My guess (as you didn't show more code, which would be required for a proper assessment) is that the actual code - not the one you just typed into the post - contains a template-id forgetValue:template < class T > T getObjectValue( const std::string id ){ if ( object_.find(id) != objects_end()){ return std::dynamic_pointer_cast<Derived<T>>(objects_.at(id))->getValue<...>(); } }Instead, try
template < class T > T getObjectValue( const std::string id ){ if ( object_.find(id) != objects_end()){ return std::dynamic_pointer_cast<Derived<T>>(objects_.at(id))->template getValue<...>(); } }