2017-06-15 81 views
0

由於C++ 17棄用std::iterator,我需要實現我自己的。原來它只是一個帶有一些typedefs的空結構。實現std :: iterator

template <class Category, class Type, class Diff = ptrdiff_t, 
    class Pointer = Type*, class Reference = Type&> 
struct iterator { 
    typedef Category iterator_catergory; 
    typedef Type value_type; 
    typedef Diff difference_type; 
    typedef Pointer pointer; 
    typedef Reference reference; 
}; 

struct dummy_iter : iterator<std::output_iterator_tag, int> {} 

這工作:

printf("%d\n", std::is_same<typename dummy_iter::pointer, int*>::value); 

但是,它不與std::iterator_traits工作:

printf("%d\n", std::is_same<typename std::iterator_traits<dummy_iter>::pointer, int*>::value); 

error: 'pointer' in 'struct std::iterator_traits<dummy_iter>' does not name a type 
+2

您不必實現自己的。 'std :: iterator'仍然在標準中,並且每個標準庫實現都需要提供它。棄用是一種警告,表示將來可能會刪除**。這並不會將其刪除,但這並不意味着它會被刪除。自1998年以來,C頭文件已被棄用,並且它們仍然活着,踢腿並被廣泛使用。 –

回答

3

你有一個錯字。本聲明:

typedef Category iterator_catergory; 

應該是這個:

typedef Category iterator_category; 

該標準規定,除非iterator_traits包含所有需要的類型定義,它成爲一個空類。參見[iterator.traits]/2:

如果迭代器具有有效的([temp.deduct])成員類型difference_type, VALUE_TYPE,指針,參考,和的iterator_category, iterator_traits應具有如下面的公開 訪問成員:

using difference_type = typename Iterator::difference_type; 
    using value_type  = typename Iterator::value_type; 
    using pointer   = typename Iterator::pointer; 
    using reference   = typename Iterator::reference; 
    using iterator_category = typename Iterator::iterator_category; 

否則iterator_traits應通過任何 上述名稱沒有成員。

+0

幹得不錯。你在一分鐘之內擊敗了我。 :-) –

相關問題