STL之traits編程技法

來源:互聯網
上載者:User

標籤:

    traits編程技法利用了“內嵌型別”的編程技巧與編譯器的template參數推導功能。

下面主要看看利用traits編程技法實現的迭代器萃取機制。

5種迭代器類型定義:

struct input_iterator_tag {};struct output_iterator_tag {};struct forward_iterator_tag : public input_iterator_tag {};struct bidirectional_iterarot_tag : public forward_iterator_tag {};struct random_access_iterator_tag : public bidirectional_iterarot_tag {};

std::iterator的定義

template <class Category, class T, class Distance = ptrdiff_t,           class Pointer = T*, class Reference = T&>struct iterator {    typedef Category    iterator_category;    typedef T           value_type;    typedef Distance    difference_type;    typedef Pointer     pointer;    typedef Reference   reference;};

    如果想和STL協同工作,自行定義的迭代器必須定義iterator_category、value_type、difference_type、pointer、reference這五大內嵌型別。為了方便,STL定義了std::iterator這個基類,自訂的迭代器只要繼承這個基類

就可以了。但要注意的是,並不是STL中的所有迭代器都繼承了這個基類,比如_deque_iterator。

"榨汁機"traits

template <class Iterator>struct iterator_traits {    typedef typename Iterator::iterator_category  iterator_category;    typedef typename Itetator::value_type         value_type;    typedef typename Iterator::difference_type    difference_type;    typedef typename Iterator::pointer            pointer;    typedef typename Iterator::reference          reference;};

    由於原生指標也是一種迭代器,但是原生指標沒有內嵌型別,因此,iterator_traits需要為原生指標提供特化版本。

template <class T>struct iterator_traits<T*> {    typedef random_access_iterator_tag  iterator_category;    typedef T         value_type;    typedef ptrdiff_t    difference_type;    typedef T*            pointer;    typedef T&          reference;};template <class T>struct iterator_traits<const T*> {    typedef random_access_iterator_tag  iterator_category;    typedef T         value_type;    typedef ptrdiff_t    difference_type;    typedef const T*            pointer;    typedef const T&          reference;};

 

  

 

STL之traits編程技法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.