您可以专门化boost::property_tree::translator_between
,以便属性树将自定义转换器用于bool
值类型。#includ
想要定制行为的客户必须能够看到(即编辑)这种专业化。这是一个工作示例:
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
// Custom translator for bool (only supports std::string)
struct BoolTranslator
{
typedef std::string internal_type;
typedef bool external_type;
// Converts a string to bool
boost::optional<external_type> get_value(const internal_type& str)
{
if (!str.empty())
{
using boost::algorithm::iequals;
if (iequals(str, "true") || iequals(str, "yes") || str == "1")
return boost::optional<external_type>(true);
else
return boost::optional<external_type>(false);
}
else
return boost::optional<external_type>(boost::none);
}
// Converts a bool to string
boost::optional<internal_type> put_value(const external_type& b)
{
return boost::optional<internal_type>(b ? "true" : "false");
}
};
/* Specialize translator_between so that it uses our custom translator for
bool value types. Specialization must be in boost::property_tree
namespace. */
namespace boost {
namespace property_tree {
template<typename Ch, typename Traits, typename Alloc>
struct translator_between<std::basic_string< Ch, Traits, Alloc >, bool>
{
typedef BoolTranslator type;
};
} // namespace property_tree
} // namespace boost
int main()
{
boost::property_tree::iptree pt;
read_json("test.json", pt);
int i = pt.get<int>("number");
int b = pt.get<bool>("enabled");
std::cout << "i=" << i << " b=" << b << "\n";
}
测试.json:
{
"number" : 42,
"enabled" : "Yes"
}
输出:
i=42 b=1
请注意,此示例假定属性树不区分大小写并使用std::string
. 如果您想BoolTranslator
更通用,则必须制作BoolTranslator
一个模板并为宽字符串和区分大小写的比较提供专业化。