title: Give access to encapsulated container
body: <pre><code>class X {
    public:
      typedef std::list&lt;int&gt; Container;
  
      // (1)
      const Container&amp; GetElements() const;
  
      // (2)
      Container::iterator ElementBegin();
      Container::iterator ElementEnd();
  
      // (3)
      CustomIterator GetElementIterator();
  
    private:
      Container m_container;
  };
  </code></pre>
  
  <p>I'm looking for a consistent and clean way of providing iterators to encapsulated containers to the caller. I came up with the three ideas marked in the source code above.</p>
  
  <ol>
  <li>Provides size(), begin() and end(), all perfect for read access. However, because the returned <code>Container</code> reference is const, you'll only be able to use <code>const_iterator</code>. Returning the reference non-const is bad, because the container itself could be modified (e.g. <code>clear()</code>).</li>
  <li>Provides non-const access to the elements, however we'd often need an own <code>size()</code> method (like <code>GetElementCount()</code>). <code>iterator::distance()</code> could be used, but that may be inefficient for some containers (where <code>operator++</code>/<code>--</code> is called repeatedly to calculate the distance).</li>
  <li>Provides a custom iterator with methods like <code>next()</code> etc. Still an own <code>size()</code> method is required.</li>
  </ol>
  
  <p>I highly bet there're nicer solutions, so if you know any, I'd be glad to see them.</p>