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;
}@ -
The fact that I hadn't found this approach documented somewhere made me suspect some hidden folly in it.