【问题标题】:How to forward declare boost::ptree::iterator如何转发声明 boost::ptree::iterator
【发布时间】:2011-05-11 21:35:24
【问题描述】:

我想在我的项目中使用 boost ptree,但是由于 ptree.hpp 导致包含大约另外 1000 个头文件,这会大大增加编译时间(例如从 1 秒到 7 秒),并且因为它需要在 20 多个不同的 cpp 文件中这是不可接受的(预编译的头文件并没有太大的改进)。所以我正在考虑将 boost ptree 封装在我自己的类中,比如

// myptree.h
#include <boost/property_tree/ptree_fwd.hpp>

class myptree {
   private:
      boost::property_tree::ptree *m_tree;

   public:
      ...
     // adding new (single value) members to the the tree
     void put(const std::string&, double);
     void put(const std::string&, int);
     void put(const std::string&, const std::string&);

     // returning (single value) members of the tree
     double get_double(const std::string&) const;
     int get_int(const std::string&) const;
     std::string get_str(const std::string&) const;

     // working with subtrees
     void push_back(const std::string&, const myptree&);
     myptree get_child(const std::string&) const;

     // import/export
     void read_from_json(const std::string&);
     void write_to_json(const std::string&) const;

};

但是,我未能以一种很好的方式实现迭代器。理想情况下,我希望将boost::property_tree::ptree::iterator 作为私有成员变量,然后可以使用我自己的成员函数在m_tree 上进行迭代,但正如我从How do I forward declare an inner class? 了解到的那样,这通常是不可能的。在此类中实现迭代器的任何优雅方式?

【问题讨论】:

标签: c++ boost forward-declaration boost-propertytree


【解决方案1】:

您的问题非常适合 Pimpl idiom,又名 编译器防火墙,又名 Handle-Body。另见article。您提出的解决方案与该成语非常相似。

要对您的客户隐藏ptree 的迭代器,请查看this article 中介绍的any_iterator 技术。

您可以找到 any_iterator herehere 的实现。

【讨论】:

    【解决方案2】:

    我对您的实际问题没有很好的答案,但是在这种情况下,预编译的标头应该是一个重大改进。您确定它实际上正在被使用并且尚未从每个编译单元中读取标头吗?进行最佳设置可能有点棘手。 (即避免使用“自动”选项)

    【讨论】:

      【解决方案3】:

      感谢您的回答。关于预编译头文件,我检查了它们是否实际被使用(g++ -H 最初显示大约 1460 个头文件,使用预编译头文件时只有大约 30 个)并且编译时间从 7 秒减少到 5.5 秒,与大约使用上述封装类时为1s。

      现在,当我尝试使用any_iterator(现在似乎也是 boost 的一部分)时,我意识到它还添加了数百个其他头文件,但仅仅包括它们并没有增加太多编译时间。所以我对 ptree 标头进行了相同的尝试,并包含 ptree.hpp 而不是 ptree_fwd.hpp 并且编译时间增加了一点(从 1.1s 到 1.8s)。因此,似乎只有在实例化 ptree 模板时才会出现严重的编译时间损失?这也可以解释为什么预编译的头文件没有那么大的帮助?懒惰,因为我的主要问题是编译时间,我可能会坚持这样的事情:

      // myptree.h
      #include <boost/property_tree/ptree.hpp>
      
      class myptree {
         private:
            boost::property_tree::ptree           m_tree;
            boost::property_tree::ptree::iterator m_it;
         ...
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        • 2011-12-30
        • 1970-01-01
        • 2012-03-07
        • 1970-01-01
        相关资源
        最近更新 更多