Boost logo

Boost :

From: scleary_at_[hidden]
Date: 2000-10-19 07:52:01


> Now, although I can insert
> derived class pointers into the original vector, the smart-pointer
versions
> of the derived classes do not have any inheritance relationship with the
> base class smart pointer and so cannot be inserted.

1) There is no way, AFAIK, to do this.

2) I don't think you have to (at least for this situation).

As you note, DerivedNodePtr is not derived from BaseNodePtr. However, they
supply templated assignment/copy construction, etc., which allows for
*implicit conversions of the underlying pointer type*. In other words, the
following code compiles fine on my system (BCB5, your mileage may vary with
compilers that don't support template members of template classes):
  #include <vector>
  #include <boost/smart_ptr.hpp>

  class BaseNode {};
  class DerivedNode : public BaseNode {};
  typedef boost::shared_ptr<BaseNode> BaseNodePtr;
  typedef boost::shared_ptr<DerivedNode> DerivedNodePtr;

  static void test2()
  {
    std::vector<BaseNodePtr> v0;
    std::vector<DerivedNodePtr> v1;
  
    v1.push_back(DerivedNodePtr(new DerivedNode));
    v0.push_back(v1[0]);
  }

The last line of code there constructs a new BaseNodePtr from a
DerivedNodePtr, which compiles because there's an implicit pointer
conversion from DerviedNode to BaseNode. (It won't compile the other way,
just like raw pointers).

> None the less, I'd never be able
> to recover the type of the DerivedNodePtr without dynamic casting on the
> referent.

What you'll end up with is a BaseNodePtr pointing to a DerivedNode
(DerivedNodePtr isn't involved). Just as if you did the same thing with raw
pointers -- you would have a BaseNode* pointing to a DerivedNode
(DerviedNode* isn't involved). Then, where before you had
"dynamic_cast<DerivedNode*>(v[0])" you could now have
"dynamic_cast<DerivedNode*>(v[0].get())".

I'm going to assume now that you're using MSVC, which won't compile the
above. Trying to think of a workaround... um... I dunno! Anyone else got
some bright ideas? The best kind of solution would be only included for
MSVC, and written so no code would have to change when/if MSVC fully
supports member templates. For anyone who has MSVC out there, how does
their std::auto_ptr handle this?

        -Steve


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk