Converting smart pointers
Here's a problem:
- You have a class named
some_class:
struct base {
virtual void some_methods() = 0;
virtual ~base();
};
struct derived: public base {
void some_methods() /*override*/;
virtual void derived_method() const;
~derived() /*override*/;
};- You have a third-party API that returns constructed
derivedby shared pointer tobaseand accepts shared pointer toconst derivedin other functions:
#include <boost/shared_ptr.hpp> boost::shared_ptr<const base> construct_derived(); void im_accepting_derived(boost::shared_ptr<const derived> p);
- You have to make the following code work:
void trying_hard_to_pass_derived() {
boost::shared_ptr<const base> d = construct_derived();
// Oops! Compile time error:
// ‘const struct base; has no member named ‘derived_method;.
d->derived_method();
// Oops! Compile time error:
// could not convert ‘d; to ‘boost::shared_ptr<const derived>;.
im_accepting_derived...