Range based for loops


#1

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..?


Tidy reverse range-based for?
#2

definitely yes :)


#3

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...


#4

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


#5

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


#6

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

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

// blah
    }
}

 

Super easy :) 


#7

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


#8

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


#9

would be pretty useful!


#10

:thumbsup: :wink:


#11

Most excellent.