勿在浮沙筑高台--P17-18

2021-07-21  本文已影响0人  Catherin_gao

一. pointer-like classes 智能指针

template<class T>
class shared_ptr{
public:
    T& operator*() const
     { return *px; }
    T* operator->() const
    { return px; }
    shared_ptr(T* p) : px(p) {}

private:
    T*    px;
    long* pn;
....
};
struct Foo{
    ....
    void method(void){....}
};

shared_ptr<Foo> sp(new Foo);
Foo f(*sp);
sp->method();  //px->method(); '->'符号消耗掉还会作用下去。

二. pointer-like classes 迭代器, 也是智能指针

template<class T, class Ref, class Ptr>
struct __list_iterator{
    typedef __list_iterator<T, Ref, Ptr> self;
    typedef Ptr pointer;
    typedef Ref refernce;
    typedef __list_node<T>* link_type;
    link_type node;
    bool operator==(const self& x) const { return node == x.node; }
    bool operator!=(const self& x) const { return node != x.node; }
    reference operator* const { return (*node).data; }
    pointer operator->() const { return &(operator*()); }
    self& operator++(){node = (link_type)((*node).next); return *this; }
    self operator++(int){self tmp = * this; ++*this; return tmp; }
    self& operator--(){node = (link_type)((*node).prev); return *this; }
    self operator--(int){self tmp = * this; --*this; return tmp; }
};

template<class T>
struct __list_node{
   void* prev;
   void* next;
   T data;
};
list<Foo>::iterator ite;
...
*ite;     //获得一个Foo object
ite->method;
  //意思是调用Foo::method();
  //相当于(*ite).method();
  //相当于&(*ite)->method();

三. function-like classes, 仿函数

template<class T>
struct identity{
    const T&
    operator()(const T& x) const{return x;}
};
template<class Pair>
上一篇 下一篇

猜你喜欢

热点阅读