I have a class that includes std :: list and wants to provide public begin () and end () for const_iterator and private begin () and end () for a simple iterator.
However, the compiler sees the closed version and complains that it is private rather than using the public version of const.
I understand that C ++ will not overload the return type (in this case const_iterator and iterator), and therefore it selects a non-constant version, since my object is not const.
Does my object end with const before calling begin () or does not overload the beginning of the name, is there any way to accomplish this?
I would think that this is a well-known pattern that people decided before, and would like to follow his example, as it is usually solved.
class myObject { public: void doSomethingConst() const; }; class myContainer { public: typedef std::list<myObject>::const_iterator const_iterator; private: typedef std::list<myObject>::iterator iterator; public: const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } void reorder(); private: iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } private: std::list<myObject> _data; }; void myFunction(myContainer &container) { myContainer::const_iterator itr = container.begin(); myContainer::const_iterator endItr = container.end(); for (; itr != endItr; ++itr) { const myObject &item = *itr; item.doSomethingConst(); } container.reorder();
A compiler error looks something like this:
../../src/example.h:447: error: `std::_List_iterator<myObject> myContainer::begin()' is private caller.cpp:2393: error: within this context ../../src/example.h:450: error: `std::_List_iterator<myObject> myContainer::end()' is private caller.cpp:2394: error: within this context
Thanks.
-William
c ++ iterator stl const function-overloading
WilliamKF
source share