3 回答
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
.
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*
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
.