Change how boost::property_tree reads translates strings to bool

前端 未结 2 1112
终归单人心
终归单人心 2020-12-29 10:07

I\'ve gotten lost in the header files for the boost property_tree and given the lack of documentation around the lower layers, I\'ve decided to ask what the easy way is to o

2条回答
  •  太阳男子
    2020-12-29 10:17

    There is also a good example at theboostcpplibraries.com.

    Based on that, I wrote for a custom parser (declaration omitted):

    boost::optional string_to_bool_translator::get_value(const std::string &s) {
        auto tmp = boost::to_lower_copy(s);
        if (tmp == "true" || tmp == "1" || tmp == "y" || tmp == "on") {
           return boost::make_optional(true);
        } else if (tmp == "false" || tmp == "0" || tmp == "n" || tmp == "off") {
          return boost::make_optional(false);
        } else {
            return boost::none;
        }
    } 
    

    It's only for bool and std::string but easily extendable.

    Then,

    boost::property_tree::ptree pt;
    ...
    string_to_bool_translator tr;
    auto optional_value = pt.get_optional(key, tr);
    

提交回复
热议问题