【发布时间】:2018-09-25 15:44:36
【问题描述】:
这是我对 boost::property_tree 的第一次体验,我找不到一种方法来重现按照文档 (How to Access Data in a Property Tree) 从树中获取值的方法。这是我为试验属性树而编写的简单代码:
#include <iostream>
#include <string>
#include <boost/property_tree/info_parser.hpp>
#include <boost/property_tree/ptree.hpp>
namespace pt = boost::property_tree;
int main(int argc, char *argv[]) {
pt::ptree tree;
tree.put("pi", 3.14159);
tree.put("name", "John Doe");
for (auto &[key, value] : tree)
std::cout << key << " : " << value.get_value<std::string>() << "\n";
std::cout << "pi : " << tree.get_value("pi") << "\n";
std::cout << "name : " << tree.get_value("name") << "\n";
auto pi = tree.get_optional<float>("pi").get();
std::cout << "pi optional : " << pi << "\n";
auto pi_found = tree.find("pi");
std::cout << "pi found : " << pi_found->second.data() << "\n";
// the commented line doesn't compile
// std::cout << "not found : " << tree.get_value<int>("null") << "\n";
std::cout << "not found : " << tree.get_value("null") << "\n";
// the line below causes an assertion error:
// Assertion failed: (this->is_initialized()), function get, file /usr/local/include/boost/optional/optional.hpp, line 1191.
// not found : Abort trap: 6
std::cout << "not found : " << tree.get_optional<int>("null").get() << "\n";
pt::write_info("ptree.info", tree);
return 0;
}
这是输出:
pi : 3.1415899999999999
name : John Doe
pi :
name :
pi optional : 3.14159
pi found : 3.1415899999999999
not found :
可以看出tree.get_value("whatever") 没有返回值,tree.get_value("null") 不会抛出异常,get_optional<whatever type> 不会编译。我的实验的行为与文档中所述的完全不同。排除导致断言错误的行会按预期创建输出信息文件。
我的环境是:
MacOS 10.11.6
macbrew installed tools and libraries
boost 1.67
clang 7.0
meson build system
【问题讨论】:
标签: c++ boost boost-propertytree