4

我想在我的项目中使用 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;

};

但是,我未能以一种很好的方式实现迭代器。理想情况下,我希望将 a作为私有成员变量,然后可以使用我自己的成员函数boost::property_tree::ptree::iterator对其进行迭代,但正如我从如何转发声明内部类中了解的那样?这通常是不可能的。在此类中实现迭代器的任何优雅方法?m_tree

4

3 回答 3

4

您的问题是Pimpl idiom(又名compiler firewall,又名Handle-Body )的一个很好的候选者。另请参阅这篇文章。您提出的解决方案与该成语非常相似。

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

any_iterator 你可以在这里这里找到实现。

于 2011-05-12T00:39:33.680 回答
3

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

于 2011-05-11T22:11:28.813 回答
0

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

现在,当我尝试使用any_iterator(现在似乎也是 boost 的一部分)时,我意识到它还添加了数百个其他头文件,但仅仅包括它们并没有增加太多编译时间。所以我对 ptree 头文件进行了同样的尝试,并包含ptree.hpp而不是ptree_fwd.hpp增加了编译时间(从 1.1 秒到 1.8 秒)。所以似乎只有在实例化 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;
   ...
};
于 2011-05-12T12:14:29.637 回答