How to clone a container of polymorphic pointers?
Assume that classes of these polymorphic pointers have a clone() virtual member function that can clone it self. Write a functor to clone the objects:
#include <functional>
#include <algorithm>
template <class T>
struct cloner : public ::std::unary_function<T*, T*>
{
T* operator () (T*& p)
{
return p->clone();
}
};
Use transform() and inserter/back_inserter/front_inserter to clone the container:
vector<PolymorphicBase*> src; // The container of polymorphic pointers
// to clone.
vector<PolymorphicBase*> tgt; // The target container to hold the
// pointers to cloned objects.
transform(
src.begin(), src.end(), // Enumerate each elements of src.
back_insert(tgt), // Insert cloned objects to tgt.
cloner<PolymorphicBase>() // Use cloner to clone each elements.
);
This tip is especially useful in copy constructor when the object hold various containers of polymorphic pointers:
class Foo
{
public:
Foo(const Foo& other)
{
transform(
other.c_.begin(), other.c_.end(),
back_insert(c_),
cloner<PolymorphicBase>()
);
}
private:
vector<PolymorphicBase*> c_;
};



Post a Comment