问题描述
可以说我有类
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;
};
现在想什么,我重写PTR和makeShared()的定义是通用的,这样从子类(ES)的情况下调用makeShared()会产生一个指向子类而不是父
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
要更清楚调用任何类继承父makeShared()会给一个指向继承类的一个实例。并呼吁使共享()的父类将使一个指向父类的一个实例
任何想法?
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 classAny ideas?
推荐答案
CRTP将在这里工作:
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> {
};
注意 makeShared
是因为它可以用的(在C ++ 11和Boost)。为你的方法更典型的名称是克隆
。
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
.
这篇关于找出类及其子里面的类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!