How can I expose iterators without exposing the container used?

前端 未结 4 1125
野性不改
野性不改 2020-12-24 08:14

I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance a

4条回答
  •  失恋的感觉
    2020-12-24 08:55

    I am unsure about what you mean by "not exposing std::vector publicly" but indeed, you can just define your typedef like that:

    typedef typename std::vector::iterator iterator;
    typedef typename std::vector::const_iterator const_iterator; // To work with constant references
    

    You will be able to change these typedefs later without the user noticing anything ...

    By the way, it is considered good practice to also expose a few other types if you want your class to behave as a container:

    typedef typename std::vector::size_type size_type;
    typedef typename std::vector::difference_type difference_type;
    typedef typename std::vector::pointer pointer;
    typedef typename std::vector::reference reference;
    

    And if needed by your class:

     typedef typename std::vector::const_pointer const_pointer;
     typedef typename std::vector::const_reference const_reference;
    

    You'll find the meaning of all these typedef's here: STL documentation on vectors

    Edit: Added the typename as suggested in the comments

提交回复
热议问题