How to provide stl like container with public const iterator and private non-const iterator?
Posted
by WilliamKF
on Stack Overflow
See other posts from Stack Overflow
or by WilliamKF
Published on 2010-03-13T18:26:26Z
Indexed on
2010/03/13
18:35 UTC
Read the original article
Hit count: 518
Hello,
I am deriving a class privately from std::list and wish to provide public begin() and end() for const_iterator and private begin() and end() for just plain iterator.
However, the compiler is seeing the private version and complaining that it is private instead of using the public const version.
I understand that C++ will not overload on return type (in this case const_iterator and iterator) and thus it is choosing the non-const version since my object is not const.
Short of casting my object to const before calling begin() or not overloading the name begin is there a way to accomplish this?
I would think this is a known pattern that folks have solved before and would like to follow suit as to how this is typically solved.
class myObject;
class myContainer : private std::list<myObject> {
public:
typedef std::list<myObject>::const_iterator myContainer::const_iterator;
private:
typedef std::list<myObject>::iterator myContainer::iterator;
public:
myContainer::const_iterator begin() const {
return std::list<myObject>::begin();
}
myContainer::const_iterator end() const {
return std::list<myObject>::end();
}
private:
myContainer::iterator begin() {
return std::list<myObject>::begin();
}
myContainer::iterator end() {
return std::list<myObject>::end();
}
};
void myFunction(myContainer &container) {
myContainer::const_iterator aItr = container.begin();
myContainer::const_iterator aEndItr = container.end();
for (; aItr != aEndItr; ++aItr) {
const myObject &item = *aItr;
// Do something const on container's contents.
}
}
The error from the compiler is 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
© Stack Overflow or respective owner