【发布时间】:2016-08-23 12:10:37
【问题描述】:
Boost PropertyTree 通过提供translator_between 的特化来允许自定义类型的序列化,但我找不到任何文档,而且代码可能相当神秘。
【问题讨论】:
-
对此有a similar question,但答案仅提供了一个示例,而不是一般描述。
Boost PropertyTree 通过提供translator_between 的特化来允许自定义类型的序列化,但我找不到任何文档,而且代码可能相当神秘。
【问题讨论】:
自定义类型CustomType 的一般模式是:
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
对于ptree 和iptree,KeyType 必须是std::string,并且通常必须与basic_ptree 的第一个模板参数相同。如果你喜欢这种事情,你可以将type 设为模板。
internal_type 和 external_type 这两个 typedef 是强制性的,它们在 detail::is_translator<Translator> 中使用 ptree_utils.hpp。
请注意,您可以将 translator_between::type 设为 typedef,但从技术上讲,您不需要这样做。我怀疑他们在所有示例中都这样做是为了使定义更漂亮。
get_value 和 put_value 的参数不一定必须是 const &,但我想不出改变它的理由。
请注意您将translator_between 声明放在何处,尤其是当您的CustomType 重载流式操作符时。在这种情况下,您可能应该将translator_between 放在运算符声明旁边。
【讨论】: