c++11中一个XMLElement类的基于Tricky-range的循环实现

Tricky range based for loop implementation for an XML Element class in c++11

本文关键字:Tricky-range 实现 循环 XMLElement 一个 c++11      更新时间:2023-10-16

如何让这样的东西同时用于元素和属性的基于范围的循环?

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

我希望能够使用这样的东西:

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

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

这样实现它是个好主意吗?还是应该更改我的设计?

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

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

child_elements函数将返回某种存储两个迭代器的类型,比如boost::iterator_range。CCD_ 3将同样返回属性元素的范围。