更改boost :: property_tree读取如何将字符串转换为bool

Aru*_*nas 14 c++ boost boost-propertytree

我已经迷失在boost property_tree的头文件中,并且由于缺少关于较低层的文档,我决定问一下简单的方法是覆盖流转换器来改变如何解析布尔值.

问题是在属性树的输入端有用户,他们可以修改配置文件.可以通过多种方式指定布尔值,例如:

dosomething.enabled=true
dosomething.enabled=trUE
dosomething.enabled=yes
dosomething.enabled=ON
dosomething.enabled=1
Run Code Online (Sandbox Code Playgroud)

默认行为是检查0或1,然后使用

std::ios_base::boolalpha 
Run Code Online (Sandbox Code Playgroud)

让流尝试以适当的方式解析当前语言环境的值...如果我们尝试将配置文件发送给国际客户,这可能是疯了.

那么什么是覆盖这种行为或bool的最简单方法呢?不仅最容易实现,而且最容易使用 - 因此我的类的用户从iptree派生而来不需要为布尔值做一些特殊的事情.

谢谢!

Emi*_*ier 21

您可以专门化,boost::property_tree::translator_between以便属性树将使用自定义转换器作为bool值类型.这种专业化必须#includ由想要自定义行为的客户可见(即ed).这是一个有效的例子:

#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";
}
Run Code Online (Sandbox Code Playgroud)

test.json:

{
    "number" : 42,
    "enabled" : "Yes"
}
Run Code Online (Sandbox Code Playgroud)

输出:

i=42 b=1
Run Code Online (Sandbox Code Playgroud)

请注意,此示例假定属性树不区分大小写并使用std::string.如果您想要BoolTranslator更通用,则必须制作BoolTranslator模板并为宽字符串和区分大小写的比较提供特化.

  • 因为知道要专攻哪个模板,所以更神奇! (2认同)
  • 实际上translator_between部分是没有必要的,因为你可以在调用property_tree的方法时指定一个自定义转换器,就像得到这样:properties.get <Scenario :: EStatus,EStatusTranslator>("status",EStatusTranslator())其中EStatusTranslator是一个翻译器喜欢你的BoolTranslator (2认同)