基于c ++ 11中的XML Element类的循环实现的棘手范围

Mih*_*şog 2 c++ foreach c++11

如何使用基于范围的元素和属性循环来完成这样的工作?

#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;
    };
}
Run Code Online (Sandbox Code Playgroud)

我希望能够使用类似的东西:

for (XML::Element &el : element) { .. }
for (XML::Attribute &at : element) { .. }
Run Code Online (Sandbox Code Playgroud)

并阻止类似的东西for (auto &some_name : element) { .. } //XML::Element or XML::Attribute?.

像这样实现它是一个好主意还是我应该改变我的设计?

Nic*_*las 5

正确的答案是为Element节点提供返回子属性和元素范围的函数.因此,你可以这样做:

for(auto &element : element.child_elements()) {...}
for(auto &attribute : element.attributes()) {...}
Run Code Online (Sandbox Code Playgroud)

你的child_elements函数会返回某种存储两个迭代器的类型,比如boost :: iterator_range.attributes同样会返回属性元素的范围.