成员函数模板

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

成员函数模板
真实指针⽀持隐式转换:1)Derived class指针可以隐式转换为Base class指针;2)"指向non-const对象"的指针可以转换成"指向const对象"的指针。

智能指针:必须编写⼀个成员函数模板。

因为我们⽆法写出所有的智能指针的构造函数,⼀旦Derived体系有新的补充就⼜要根据其他智能指针构造⾃⼰,实在太多了,根本不能写完。

因为⼀个template可以被⽆限量具现化,以⾄于⽣成⽆限量函数,所以我们不写构造函数,⽽是写⼀个构造模板,称为成员函数模板。

成员函数模板:
根据⾃⼰的理解,我认为成员函数模板其实就是放在class⾥⾯的函数模板。

如果声明member template⽤于"泛化copy构造"或"泛化assignment操作",你还是需要声明正常的copy构造函数和copy assignment操作符。

什么叫泛化构造函数呢?
template<class T>
classshared_ptr{
public:
template<class Y>
explicit shared_ptr(Y* p);
template<class Y>
shared_ptr(shared_ptr<Y> const& r); //泛化copy构造函数
template<class Y>
explicit shared_ptr(weak_ptr<Y> const& r);
template<class Y>
explicit shared_ptr(auto_ptr<Y> const& r);
template<class Y>
shared_ptr& operator=(shared_ptr<Y> const& r); //赋值
template<class Y>
shared_ptr& operator=(auto_ptr<Y> const& r);
……
};
当T和Y类型⼀样时,泛化copy构造函数就是普通的copy构造函数了。

相关文档
最新文档