Boost property_tree: multiple values per key, on a

2019-07-22 02:06发布

On this topic, Boost property_tree: multiple values per key, a method is proposed to read multiples keys of a boost tree. I will paste a modified version below

template<int dim>
struct my_vector
{
  std::vector<double> a_vector;
};

The translator would be:

template<int dim>
struct my_vector_translator
{
  typedef std::string    internal_type;
  typedef my_vector external_type;
  // Get a my_vector from a string
  boost::optional<external_type> get_value(const internal_type& str)
  {
    if (!str.empty())
    {
      std::vector val;
      val.resize(dim)
      std::stringstream s(str);
      double temp;
      for (int i=0, i < dim; ++i){
          s >> temp;
          val.a_vector[i] = temp;
      return boost::optional<external_type>(val);
    }
    else
      return boost::optional<external_type>(boost::none);
  }

};

And now, how should i do to register the translator properly ?

namespace boost { namespace property_tree 
{
  template<typename Ch, typename Traits, typename Alloc> 
  struct translator_between<std::basic_string< Ch, Traits, Alloc >, my_vector<it want something here of course, where do i get it from ?> >
  {
    typedef my_vector_translator<it want something here of course, where do i get it from ?> type;
  };
} }

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

  pt.get<my_vector ??and here where do i put the size ?>("box.x");

And somehow i feel that the class my_vector is useless. Couldn't I work directly with std::vector ?

I would like something like:

pt.get<std::vector<double>, 3>("mesh.a_line_where_i_know_i_have_3_doubles_to_read");

Thank you.

1条回答
冷血范
2楼-- · 2019-07-22 02:39

It seems to me that size is already the template argument to the my_vector class template.

So

pt.get<my_vector<3> >("box.x");

should be good

Registering:

A partial specialization can introduce extra template arguments, so just add size_t N to the list:

namespace boost { namespace property_tree {
    template<typename Ch, typename Traits, typename Alloc, size_t N> 
        struct translator_between<std::basic_string<Ch, Traits, Alloc>, my_vector<N> >
        {
            typedef my_vector_translator<N> type;
        };
} }
查看更多
登录 后发表回答