条款45:运用成员函数模板接受所有兼容类型

来源:互联网 发布:ardupilot3.3源码下载 编辑:程序博客网 时间:2024/05/22 13:07
/*条款45:运用成员函数模板接受所有兼容类型*///真实指针做得好的一点是支持隐式转换,子类指针->基类指针,非常对象指针->常对象指针#include<iostream>using namespace std;class Top{};class Middle:public Top{};class Bottom:public Middle{};/*Top*pt1 = new Middle;//子类到基类的指针转换Top*pt2 = new Bottom;//孙子类到基类指针转换const Top*pct2 = pt1;//非常转换常的指针转换*//*template<typename T>class SmartPtr{public:explicit SmartPtr(T*realPtr);};SmartPtr<Top>pt1=SmartPtr<Middle>(new Middle);//将SmarPtr<Middle>转换为SmartPrt<Top>SmartPtr<Top>pt2=SmartPtr<Bottom>(new Bottom);SmartPtr<const Top>pct2 = pt1;//然而上面三个转换并不成立,因为他们实例出的对象没有继承关系我们想的是怎么编写出一个智能指针的构造函数来满足我们的转型需要,并且有通用性这时我们想到了成员模板*/template<typename T>class SmartPtr{public:template<typename U>//SmartPtr(const SmartPtr<U>&other);//这里可以根据SmartPtr<U>生成一个SmartPtr<T>,而u和v的类型是同一个template的不同具现体,我们称之为泛化拷贝构造函数//而这个构造函数也并未声明为explicit是蓄意的,因为原始指针类型之间的转换是隐式转换,所以让智能指针仿效这种行径也属合理//如果这里想提供一个和智能指针的一个get成员函数返回智能指针对象所持有的那个原始指针 的副本,我们可以在构造模板中实现代码中的约束转换行为SmartPtr(const SmartPtr<U>&other):heldPtr(other.get()){}T*get()const{return heldPtr;}private:T* heldPtr;}//成员函数模板常扮演的另一个角色是支持赋值操作template<class T>class shared_ptr{public:template<class Y>explicit shared_ptr(Y*P);template<class Y>shared_ptr(shared_ptr<Y>const&r);template<class Y>explicit shared_tr(weak_ptr<Y>const&r);template<class Y>explicit shared_ptr(auto_ptr<Y>&r);template<class Y>shared_ptr&operator=(shared_ptr<Y> const&r);template<class Y>shared_ptr&operator=(auto_ptr<Y>&r);//.上面的构造函数除泛化拷贝构造函数外都 是explicit,就是说可以由一个auto_ptr可以隐式转换成另一个auto_ptr,内置类型则不可以 ,除此之外还需要声明正常的拷贝构造和拷贝赋值.}int main(){return 0;}

0 0
原创粉丝点击