考慮下面的代碼:的boost :: iterator_facade運營商 - >()編譯失敗
#include <boost/iterator/iterator_facade.hpp>
#include <map>
// Class implements an stl compliant iterator to access the "sections" stored within a configuration.
template < typename _Iterator, typename _Reference >
class Section
: public boost::iterator_facade<
Section< _Iterator, _Reference >,
_Iterator,
boost::random_access_traversal_tag,
_Reference
>
{
private:
// Define the type of the base class:
typedef boost::iterator_facade<
Section< _Iterator, _Reference >,
_Iterator,
boost::random_access_traversal_tag,
_Reference
> base_type;
public:
// The following type definitions are common public typedefs:
typedef Section< _Iterator, _Reference > this_type;
typedef typename base_type::difference_type difference_type;
typedef typename base_type::reference reference;
typedef _Iterator iterator_type;
public:
explicit Section(const iterator_type it)
: m_it(it)
{ }
// Copy constructor required to construct a const_iterator from an iterator:
template < typename _U >
Section(const Section< _U, _Reference > it)
: m_it(it.m_it)
{ }
private:
// The following classes are friend of this class to ensure access onto the private member:
friend class boost::iterator_core_access;
template < typename _Iterator, typename _Reference > friend class Section;
void increment(){ ++m_it; } // Advance by one position.
void decrement(){ --m_it; } // Retreat by one position.
void advance(const difference_type& n){ m_it += n }; // Advance by n positions.
bool equal(const this_type& rhs) const{ return m_it == rhs.m_it; } // Compare for equality with rhs.
reference dereference() const { return m_it->second; } // Access the value referred to.
difference_type distance_to(const this_type& rhs) const{ return rhs.m_it - m_it; } // Measure the distance to rhs.
private:
// Current "section" iterator:
iterator_type m_it;
};
struct Data
{
void f() const
{ }
};
typedef std::map< int, Data > map_type;
typedef Section< const map_type::const_iterator, const Data& > iterator_type;
map_type g_map;
iterator_type begin()
{
return iterator_type(g_map.begin());
}
void main()
{
iterator_type i = begin();
// i->f(); // <--- error C2039: 'f' : is not a member of 'std::_Tree_const_iterator<_Mytree>'
(*i).f();
}
所以迭代器的外觀應返回的數據類型的引用。這在調用解引用操作符時很好,但在調用operator - >()時編譯失敗。所以我有點困惑,因爲operator - >()試圖返回一個std :: map :: iterator。有任何想法嗎 ?
再次是一個很好的答案。非常感謝。是的,這是一個誤解如何使用值參數。現在它按預期工作! – Mark