Andreas Haferburg
Andreas Haferburg

Reputation: 5510

How do I extend boost property_tree to handle custom types?

Boost PropertyTree allows serialization of custom types by providing a specialization of translator_between, but I couldn't find any documentation, and the code can be quite cryptic.

Upvotes: 1

Views: 1355

Answers (1)

Andreas Haferburg
Andreas Haferburg

Reputation: 5510

The general pattern for a custom type CustomType is:

namespace boost {
namespace property_tree {

template<>
struct translator_between<KeyType, CustomType>
{
  struct type {
    typedef KeyType internal_type;
    typedef CustomType external_type;
    boost::optional<external_type> get_value(const internal_type& str);
    boost::optional<internal_type> put_value(const external_type& obj);
  };
};

} // namespace property_tree
} // namespace boost

KeyType must be std::string for ptree and iptree, and in general must be identical to the first template argument of your basic_ptree. You could make type a template if you're into that sort of thing.

The two typedefs internal_type and external_type are mandatory, they are used in detail::is_translator<Translator> in ptree_utils.hpp.

Note that you could make translator_between::type a typedef, but you don't technically need to. I suspect they do it in all the examples to make the definition marginally prettier.

The arguments of get_value and put_value don't necessarily need to be const &, but I can't think of a reason to change that.

Beware in general of where you put your declarations of translator_between, especially if the streaming operators are overloaded for your CustomType. In this case you should probably put the translator_between next to the declarations of the operators.

Upvotes: 3

Related Questions