【问题标题】:How do I extend boost property_tree to handle custom types?如何扩展 boost property_tree 来处理自定义类型?
【发布时间】:2016-08-23 12:10:37
【问题描述】:

Boost PropertyTree 通过提供translator_between 的特化来允许自定义类型的序列化,但我找不到任何文档,而且代码可能相当神秘。

【问题讨论】:

  • 对此有a similar question,但答案仅提供了一个示例,而不是一般描述。

标签: boost-propertytree


【解决方案1】:

自定义类型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

对于ptreeiptreeKeyType 必须是std::string,并且通常必须与basic_ptree 的第一个模板参数相同。如果你喜欢这种事情,你可以将type 设为模板。

internal_typeexternal_type 这两个 typedef 是强制性的,它们在 detail::is_translator&lt;Translator&gt; 中使用 ptree_utils.hpp

请注意,您可以将 translator_between::type 设为 typedef,但从技术上讲,您不需要这样做。我怀疑他们在所有示例中都这样做是为了使定义更漂亮。

get_valueput_value 的参数不一定必须是 const &amp;,但我想不出改变它的理由。

请注意您将translator_between 声明放在何处,尤其是当您的CustomType 重载流式操作符时。在这种情况下,您可能应该将translator_between 放在运算符声明旁边。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2015-07-21
    • 2013-03-18
    • 1970-01-01
    相关资源
    最近更新 更多