Give access to encapsulated container

后端 未结 6 1235
借酒劲吻你
借酒劲吻你 2021-01-13 02:38
class X {
  public:
    typedef std::list Container;

    // (1)
    const Container& GetElements() const;

    // (2)
    Container::iterator Element         


        
6条回答
  •  臣服心动
    2021-01-13 03:28

    A mix of (2) and (3) would probably be what I'd do :

    class X {
      public :
        typedef std::list ElementContainer;
        typedef ElementContainer::size_type ElementSizeType;
        typedef ElementContainer::iterator ElementIterator;
        typedef ElementContainer::const_iterator ConstElementIterator;
    
        ElementIterator elementBegin() { return m_container.begin(); }
        ElementIterator elementEnd() { return m_container.end(); }
    
        ConstElementIterator elementBegin() const { return m_container.begin(); }
        ConstElementIterator elementEnd() const { return m_container.end(); }
    
        ElementSizeType elementSize() const { return m_container.size(); }
    
      private :
        ElementContainer m_container;
    };
    

    It still leaves room to write custom iterators (by changing the typedefs), but as long as the ones provided by the container are ok, they can be used.

提交回复
热议问题