This is my first experience with boost::property_tree and I can't find a way to reproduce the way to get values from a tree following the documentation (How to Access Data in a Property Tree). This is the simple code that I wrote to experiment with 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;
}
This is the output:
pi : 3.1415899999999999
name : John Doe
pi :
name :
pi optional : 3.14159
pi found : 3.1415899999999999
not found :
As can be seen tree.get_value("whatever")
returns no value, tree.get_value("null")
does not throw an exception and get_optional<whatever type>
does not compile. My experiment behaves way too different from the stated in the documentation. Excluding the line that causes the assertion error creates the output info file as expected.
My environment is:
MacOS 10.11.6
macbrew installed tools and libraries
boost 1.67
clang 7.0
meson build system