Re: [Boost-users] polymorphism and boost::shared_ptr
On 9/7/07, Brad Ryder
typedef boost::shared_ptr<A> shPtrA; typedef boost::shared_ptr<B> shPtrB; typedef boost::shared_ptr<C> shPtrC;
class A {
void AddChild(shPtrA& child); private: std::vector<shPtrA> m_children; }
class B : public A {
}
class C: public B {
}
main() { A base; shPtrB spB(new B()); shPtrC spC(new C());
// I dont want to typecast spB or spC
A.AddChild( (shPtrA) spB); A.AddChild( (shPtrA) spC); }
Hello, I am also new to the list, and saw your question in the archives. You don't need to use static_pointer_cast<> or limit yourself to using base class shared_ptr<>s, as has been suggested. The solution is to pass by value instead of by reference. Then the compiler has a chance to perform an implicit conversion from one shared_ptr type to another. In other words, just remove the "&" from the signature of AddChild(). void AddChild(shPtrA child); The conversion won't occur when you pass by reference because shPtrB does not inherit from shPtrA. HTH -Dan
participants (1)
-
Daniel P Furlani