How do I extend boost property tree to support my own types?
e.g. I want to write
boost::property_tree::basic_ptree<std::string,std::string> xml;
...
xml.get<int>("level"),
xml.get<double>("accuracy"),
xml.get<Ship>("sauce_pan"),
...
And then I guess somewhere I'd like to describe how to get a Ship
from a boost::property_tree::basic_ptree<std::string,std::string>
or something similar.
You need to provide a default constructor for Ship
and a stream input operator:
struct Ship {
friend std::istream& operator>>(std::istream& s, Ship& e) {
/* read ship data from s */
return s;
}
};
Unfortunately, I'm not sure if this is an official feature of property_tree
as I can not find it in the documentation.
For more fine-grained access get
also takes a Translator
as it's second argument.
struct ShipTranslatorJSON {
// the type we return
typedef Ship external_type;
// the type expect as an argument
typedef std::string internal_type;
boost::optional< external_type > get_value(const internal_type&) {
return external_type();
}
// only required when you actually use put
// boost::optional< T > put_value(const T &);
};
// use as
xml.get<Ship>("sauce_pan", ShipTranslatorJSON());
This method also seems more "official", although nothing in the documentation actually explains what a Translator really is.