c++11 - How do I implement polymorphism with std::shared_ptr? -
i have seen of other questions on topic, have still not found answer - guess i'm missing something:
i defined 2 simple test classes:
class testbase { public: testbase ( ) { }; ~ testbase ( ) { }; protected: inline virtual int getint ( ) { return 0; } }; class testderived : public testbase { protected: inline int getint ( ) override { return 1; } };
i declared typedefs simplify usage std::shared_ptr:
typedef std::shared_ptr<testbase> spbase; typedef std::shared_ptr<testderived> spderived;
problem: cannot compile code use these shared_ptr
declarations polymorphically, though base
in these cases instance of spderived
:
spbase base; spderived derived = static_cast < spderived > ( base );
error: no matching function call ‘std::shared_ptr::shared_ptr(spbase&)
spderived derived = dynamic_cast < spderived > ( base );
error: cannot dynamic_cast ‘base’ (of type ‘spbase {aka class std::shared_ptr}’) type ‘spderived {aka class std::shared_ptr}’ (target not pointer or reference)
spderived derived = static_pointer_cast < spderived > ( base );
error: conversion ‘std::shared_ptr >’ non-scalar type ‘spderived {aka std::shared_ptr}’ requested
spderived derived = dynamic_pointer_cast < spderived > ( base );
error: conversion ‘std::shared_ptr >’ non-scalar type ‘spderived {aka std::shared_ptr}’ requested
i'm using c++11 on ubuntu 14.04 box default gcc tool chain. compiler gcc-4.9. doing wrong? can't shared_pointer used polymorphically?
a type passed in std::static_pointer_cast
, std::dynamic_pointer_cast
first type template argument type of converted pointer's type itself, not of smart pointer type:
static_pointer_cast<t>(arg); .~~~^ v template <class t, class u> .~~~~^ v shared_ptr<t> static_pointer_cast(const shared_ptr<u>& r); dynamic_pointer_cast<t>(arg); .~~~~^ v template <class t, class u> .~~~~^ v shared_ptr<t> dynamic_pointer_cast(const shared_ptr<u>& r);
with said, call below:
spbase base = std::make_shared<testderived>(); spderived derived = std::dynamic_pointer_cast<spderived::element_type>(base); // or: spderived derived2 = std::dynamic_pointer_cast<testderived>(base);
Comments
Post a Comment