模板中实现继承(成员函数模板(之一:泛化copy构造函数))
真实指针做得很好的一件事是支持隐式转换(implicit conversion)。Derived class指针可以隐式转换为base class指针,“指向non-const对象”的指针可以转换为“指向const对象”….等等。
class grapa{...};
class dad:public grapa{...};
class son:public dad{...};
grapa* pt1 = new dad;
grapa* pt2 = new son;
const grapa* pct = pt1;//“指向non-const对象”的指针可以转换为“指向const对象”
但是在用户自定的智能指针中模拟上述转换有点麻烦。
同一个template的不同具现体之间并不存在什么与生俱来的固有关系(也就是说,如果以带有base-derived关系的B,D两个类型分别具现化某个template,产生出来的两个具现体并不带有base-derived关系)
成员函数模板(之一:泛化copy构造函数)
template<typename T>
class Smartptr{
public:
template<typename U>
Smartptr(const Smartptr<U>& other);
};//对任何类型T和任何类型U,这里可以根据Smartptr<U>生成一个Smartptr<T>,类型T和类型U产生同一个template的不同具现体。
但必须从某方面对成员函数模板进行拣选或筛除,例如我们不希望根据Smartptr< base >创建一个Smartptr< derived>
template<typename T>
class Smartptr{
public:
template<typename U>
Smartptr(const Smartptr<U>& other):heldptr(other.get()){}
T* get() const {return heldptr;}
private:
T* heldptr;
};//该泛化copy构造函数只有当存在一个隐式转换可将U*指针转为T*指针时才能通过编译。
成员函数模板也可支持赋值操作
template<class T>
class shared_ptr{
public:
//构造
template<class Y>
explicit shared_ptr(Y* p);//来自任何兼容的内置指针,从某个内置指针隐式转换至shared_ptr类型是不被允许
template<class Y>
shared_ptr(shared_ptr<Y> const& p);//从某个shared_ptr类型隐式转换至另一个shared_ptr类型是被允许的
template<class Y>
explicit shared_ptr(auto_ptr<Y>& r);//从某个auto_ptr类型隐式转换至一个shared_ptr类型是不允许的
//赋值
template<class Y>
shared_ptr& operator=(shared_ptr<Y> const& p);
}
在class内声明泛化copy构造函数(member function template)并不会阻止编译器生成它们自己的copy构造函数(一个non-template)。因此如果你不想使用编译器的copy构造函数,则可以选择自己实现
template<class T>
class shared_ptr{
public:
//构造
shared_ptr(shared_ptr const& r);//copy构造函数
template<class Y>
shared_ptr(shared_ptr<Y> const& p);//泛化copy构造函数
//赋值
template<class Y>
shared_ptr& operator=(shared_ptr<Y> const& p);
};