Range based for loops

Hey folks - would a range based for loop solution be nice for anyone else? 

void func(ValueTree & tree)
{
  for (auto & child: tree.children())
    doSomething(child); 

  for (auto & property: tree.properties())
    doSomethingElse(property); 
}

And similarly for children of components and other important objects..?

definitely yes :)

Maybe, for example, as a class inside class ValueTree { ... }; 

    /** Provides an STL compatible iterator for the children. */

    class ChildrenConnector
    {
    public:
        ChildrenConnector(ValueTree & tree) : tree(tree) {}

        class Iterator
        {
        public:
            Iterator(ValueTree & tree, int position) : tree(tree), pos(position) {}
            Iterator & operator++() { ++pos; return *this; }
            bool operator!= (const Iterator & other) const { return other.pos != pos || other.tree != tree; }
            ValueTree operator * () const { return tree.getChild(pos); }

        private:
            ValueTree & tree;
            int pos;
        };

        Iterator begin()    { return Iterator(tree, 0); }
        Iterator end()      { return Iterator(tree, tree.getNumChildren()); }

        private:
            ValueTree & tree;
    };

    /** Obtain an object that can be used with range based for-loops over the children. */

    ChildrenConnector children() { return ChildrenConnector(*this); }

And similarly for the Properties. 

PropertyConnector properties() { return PropertyConnector(*this); }

Might need some fancy polish to work with more of the STL functions - but that works for the range for-loop.   And seems to generate some pretty tight code...

Overloading std::begin and std::end should make most stuff work.

It would, but there are two different containers inside ValueTree for example, properties and children.  I think that preculdes that approach?

Ah - but I can just use it like this and it's okay: :) 

void DeviceTreeDataPanel::refreshDeviceListFromState()
{
    for (auto c : ChildrenConnector(tree))
    {

// blah
    }
}

 

Super easy :) 

Any chance of this or similar making it into the official ValueTree class? 

Yes, there's a good chance, as I'd find it useful too! Just need to find time to do it!

1 Like

would be pretty useful!

:thumbsup: :wink:

2 Likes

Most excellent.