Reputation: 2519
Lets say I have the class
template<typename PointT>
class Parent {
public:
typedef boost::shared_ptr<Parent<PointT> > Ptr;
inline Ptr
makeShared ()
{
return Ptr (new Parent<PointT> (*this));
}
};
template<typename PointT>
class Child : public Parent {
public:
typedef boost::shared_ptr<Child<PointT> > Ptr;
};
Now what I'd like to rewrite the definition of Ptr and makeShared() to be generic, so that calling makeShared() from child class(es) instances would yield a pointer to the child class not the parent
To make it more clear calling makeShared() on any class inheriting Parent would give a pointer to an instance of that inheriting class. and calling make shared() on the parent class would give a pointer to an instance of Parent class Any ideas?
Upvotes: 0
Views: 179
Reputation: 157354
CRTP will work here:
template<typename Child>
class Parent {
public:
typedef boost::shared_ptr<Child> Ptr;
inline Ptr
makeShared ()
{
return Ptr (new Child(*static_cast<Child *>(this)));
}
};
template<typename PointT>
class Child : public Parent<Child> {
};
Note that makeShared
is a fairly confusing name as it could be confused with shared_from_this
(in C++11 and Boost). A more typical name for your method is clone
.
Upvotes: 2