我有一个类,其中包括std::list,并希望为const_iterator提供公共的begin()和end(),并为普通iterator提供私有的begin()和end()。
然而,编译器看到了私有版本,并抱怨它是私有的,而不是使用公共的const版本。
我知道C++不会根据返回类型(在这种情况下是const_iterator和iterator)进行重载,因此它选择非const版本,因为我的对象不是const。
除了调用begin()之前将我的对象强制转换为const或者不重载名字begin之外,是否有一种实现这个目标的方法?
我认为这是一个已知的模式,人们在以前解决过这个问题,并且想跟随通常的解决方案。
编译器的错误大概是这样的:
然而,编译器看到了私有版本,并抱怨它是私有的,而不是使用公共的const版本。
我知道C++不会根据返回类型(在这种情况下是const_iterator和iterator)进行重载,因此它选择非const版本,因为我的对象不是const。
除了调用begin()之前将我的对象强制转换为const或者不重载名字begin之外,是否有一种实现这个目标的方法?
我认为这是一个已知的模式,人们在以前解决过这个问题,并且想跟随通常的解决方案。
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(); // Do something non-const on container itself.
}
编译器的错误大概是这样的:
../../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