Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to construct a custom const_iterator with const data?
    primarykey
    data
    text
    <p>I'm writing the iterator classes for a custom container (some hash map class), let's call this container <code>Map</code>.</p> <p>For a couple of reasons it seems handy to derive <code>iterator</code> from <code>const_iterator</code> and I already did this in some other custom container (an array class), which works great, so I want to stick to this pattern.</p> <p>But now that leads to the following problem (which is quite general/abstract, I'm sorry):</p> <p>Whatever <code>const_iterator</code>'s critical data member is (it might be a <code>Map</code> reference, or a pointer to <code>Map::Elements</code>, many ways are possible), <strong>it needs to be non-const</strong> so both <code>const_iterator</code> and the derived <code>iterator</code> can utilize it meaningfully in their methods.</p> <p>But how can this non-const data member, in a proper way, be initialized when dealing with a const <code>Map</code> object (e.g. calling the method <code>const_iterator Map::Begin( void ) const</code>)?</p> <hr> <p>To illustrate my question bit, I wrote some example code that solves the problem by using const_cast which, I suppose, is bad style:</p> <pre><code>#include &lt;vector&gt; template&lt; typename K, typename T &gt; class Map { public: class const_iterator { public: const_iterator( Map const &amp; a_Map, int a_Index ) : m_Index( a_Index ), m_Map( const_cast&lt; Map &amp; &gt;( a_Map ) ) // Note the use of const_cast { } private: Map &amp; m_Map; int m_Index; }; class iterator : public const_iterator { public: T &amp; operator * ( void ) { return m_Map.mElements[ m_Index ]; } }; public: const_iterator Begin( void ) const { return const_iterator( *this, 0 ); } iterator Begin( void ) { return iterator( *this, 0 ); } private: std::vector&lt; T &gt; m_Elements; }; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload