Effective C++第七章-模板和泛型编程之模板中实现继承

模板中实现继承(成员函数模板(之一:泛化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);
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值