2

How can I make something like this work with range based loops for both Elements and Attributes?

#include <list>
#include "XMLAttribute.h"

namespace XML
{
    class Element
    {
        private:
            typedef std::list<Attribute> attribute_container;
            typedef std::list<Element> element_container;

        public:
            XMLElement();

            bool has_attributes() const;
            bool has_elements() const;
            bool has_data() const;

            const std::string &name() const;
            const std::string &data() const;

        private:
            std::string _name;
            std::string _data;

            attribute_container _attributes;
            element_container _elements;
    };
}

I would like to be able to use something like:

for (XML::Element &el : element) { .. }
for (XML::Attribute &at : element) { .. }

And block something like for (auto &some_name : element) { .. } //XML::Element or XML::Attribute?.

Is it a good idea to implement it like this or should I change my design?

1 Answer 1

5

The correct answer is to give Element nodes functions that return ranges of child attributes and elements. Thus, you can do this:

for(auto &element : element.child_elements()) {...}
for(auto &attribute : element.attributes()) {...}

Your child_elements function would return some kind of type that stores two iterators, like a boost::iterator_range. attributes would likewise return a range for attribute elements.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.