Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Easy foreach for custom container - but is it legal?
Forum Updated to NodeBB v4.3 + New Features

Easy foreach for custom container - but is it legal?

Scheduled Pinned Locked Moved General and Desktop
3 Posts 2 Posters 1.4k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Asperamanca
    wrote on last edited by
    #1

    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;
    }@

    1 Reply Last reply
    0
    • A Offline
      A Offline
      andre
      wrote on last edited by
      #2

      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.

      1 Reply Last reply
      0
      • A Offline
        A Offline
        Asperamanca
        wrote on last edited by
        #3

        The fact that I hadn't found this approach documented somewhere made me suspect some hidden folly in it.

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved