Easy foreach for custom container - but is it legal?
-
Sometimes, I need a custom container that can do something extra the standard containers don't do. Often, it's just a wrapper around a standard Qt container, with some extra methods and/or bookkeeping.
e.g.
@class CoolClass
{
// Something cool here
};class CoolClassList
{
public:
// Typical list access methods
// Some nifty extra stuff
private:
// It's really only a wrapped QList
QList<CoolClass> m_List;
}@I found a pretty simple way to make this container foreach'able. But "am I doing it right"?
@class CoolClassList
{
public:
class const_iterator : public QList<CoolClass>::const_iterator
{
public:
friend class CoolClassList;
private:
const_iterator(QList<CoolClass>::const_iterator iterator)
: QList<CoolClass>::const_iterator(iterator)
{
}
};const_iterator begin() const
{
return m_List.constBegin();
}const_iterator end() const
{
return m_List.constEnd();
}// Typical list access methods
// Some nifty extra stuff
private:
// It's really only a wrapped QList
QList<CoolClass> m_List;
}@ -
Why not? Qt's foreach on containers indeed is implemented in terms of the combination of the begin and end const iterators. All you need to do is make these iterators available for your container class, and that is what you are doing.
-
The fact that I hadn't found this approach documented somewhere made me suspect some hidden folly in it.