Chinaunix首页 | 论坛 | 博客
  • 博客访问: 296302
  • 博文数量: 148
  • 博客积分: 4365
  • 博客等级: 上校
  • 技术积分: 1566
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-05 21:38
文章分类
文章存档

2014年(2)

2013年(45)

2012年(18)

2011年(1)

2009年(54)

2008年(28)

我的朋友

分类: C/C++

2013-01-16 12:32:11

当模板类型可以(或者需要能够)相互转换时,使用成员函数模板接受所有的兼容类型。

shared_ptr就写的比较明显,可以是内置类型或其它智能指针,注意shared_ptr的定义 template

成员函数处的模板都是 template ,不冲突。

注意第二个成员函数,考构,没有带explicit,可以通过它进行隐式转换。

shared_ptr作为一个模板类,T,Y是不同的具现体,这样的考构成为泛化的考构(generalized)。

template class shared_ptr {
public:
  template                                     // construct from
    explicit shared_ptr(Y * p);                         // any compatible
  template                                     // built-in pointer,
    shared_ptr(shared_ptr const& r);                 // shared_ptr,
  template                                     // weak_ptr, or
    explicit shared_ptr(weak_ptr const& r);          // auto_ptr
  template
    explicit shared_ptr(auto_ptr& r);
  template                                     // assign from
    shared_ptr& operator=(shared_ptr const& r);      // any compatible
  template                                     // shared_ptr or
    shared_ptr& operator=(auto_ptr& r);              // auto_ptr
......
}
泛化的考构与编译期默认合成的考构(非模板的)不冲突,定义了前者没有后者时,编译期仍会默认合成,同理

赋值运算符也是如此。

template class shared_ptr {
public:
  shared_ptr(shared_ptr const& r);                 // copy constructor
  template                                // generalized
    shared_ptr(shared_ptr const& r);            // copy constructor
  shared_ptr& operator=(shared_ptr const& r);      // copy assignment
  template                                // generalized
    shared_ptr& operator=(shared_ptr const& r); // copy assignment
  ...
};

阅读(389) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~