0
4

3 回答 3

2

Add another constructor:

template <typename U>
Container(Container<U> const & ref,
          typename std::enable_if<std::is_base_of<T, U>::value, int>::type = 0)
: obj_(ref.obj_)
{ }

I added the enable_if part to make sure that this new constructor template only participates in overload resolution when the type U is actually derived from T.

于 2012-08-14T14:33:51.513 回答
1

Container<A> and Container<B>are totally different class.

You can have something like container_cast<T>(U) that converts a Container<A> to Container<B>

container_cast will construct another Container<T> by taking the obj_ Container<U> and casting that obj_ to T*

于 2012-08-14T14:35:31.013 回答
-1

Instead of using the container, use an iterator pair, which is nicely convertible to base class. It solves the problem, and cleans up the code in one go.


EDIT: after more info was given, I change my answer to this:

Use boost::shared_ptr.

于 2012-08-14T14:37:28.940 回答