Boost property_tree: multiple values per key

て烟熏妆下的殇ゞ 提交于 2019-11-29 08:12:27

The standard property_tree handles only one string value per key since it is defined as:

typedef basic_ptree<std::string, std::string> ptree;

So, the only option is to use strings and parse them. I think the best method is to define a new class that stores the low and high values and then create a translator class for the get and set methods. For example:

struct low_high_value
{
  low_high_value() : m_low(0), m_high(0) { }
  low_high_value(double low, double high) : m_low(low), m_high(high) { }
  double m_low;
  double m_high;
};

The translator would be:

struct low_high_value_translator
{
  typedef std::string    internal_type;
  typedef low_high_value external_type;
  // Get a low_high_value from a string
  boost::optional<external_type> get_value(const internal_type& str)
  {
    if (!str.empty())
    {
      low_high_value val;
      std::stringstream s(str);
      s >> val.m_high >> val.m_low;
      return boost::optional<external_type>(val);
    }
    else
      return boost::optional<external_type>(boost::none);
  }

  // Create a string from a low_high_value
  boost::optional<internal_type> put_value(const external_type& b)
  {
    std::stringstream ss;
    ss << b.m_low << " " << b.m_high;
    return boost::optional<internal_type>(ss.str());
  }
};

The previous get_value method is very simple. It should be improved if the file could be written by the user.

This class should be registered using:

namespace boost { namespace property_tree 
{
  template<typename Ch, typename Traits, typename Alloc> 
  struct translator_between<std::basic_string< Ch, Traits, Alloc >, low_high_value>
  {
    typedef low_high_value_translator type;
  };
} }

After you include the previous code, you can use property_tree as:

  pt.get<low_high_value>("box.x")
  pt.put("box.u", low_high_value(-110, 200));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!