boostorg / property_tree

Boost.org property_tree module
http://boost.org/libs/property_tree
55 stars 92 forks source link

Getting unsigned of value with negative number should throw a ptree_bad_data #120

Open Pokawa opened 9 months ago

Pokawa commented 9 months ago

As of now ptree will not complain about a negative value and will happily cast it to unsigned type. If that's expected then I think it's highly unintuitive.

    boost::property_tree::ptree pt;
    pt.put("foo", "-1");
    std::cout << pt.get<unsigned>("foo") << std::endl; // 4294967295
ashtum commented 9 months ago

The ptree stores the string representation of values and uses stream_translator for retrieving and setting values. In your example, the process resembles the following:

std::stringstream ss{"-1"};
unsigned i;
ss >> i;
std::cout << i << std::endl;

You can provide your custom translator by utilizing this overload of ptree::get: https://github.com/boostorg/property_tree/blob/8080ecd14f2d952a4bb7ae869fc0f54f54f5a31f/include/boost/property_tree/ptree.hpp#L381