EML
EML

Reputation: 10280

property_tree: cannot set a default property value?

The code below reads a property from an ini file. However, I want the property to have a default value. I do this with put, before reading the ini file, and then retrieving the property with get.

This works fine if the default isn't required, and the program outputs testval is 2. However, if I comment out the entry in the ini file (as shown), the program outputs No such node (foo.bar). In other words, pt.put is not setting the default value. Any ideas why? I'm on Boost 105300.

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>

int main() {
   boost::property_tree::ptree pt;
   int testval = 0;

   try {
      pt.put("foo.bar", 1);               // set a default value
      boost::property_tree::ini_parser::read_ini("test.ini", pt);

      testval = pt.get<int>("foo.bar");

   } catch(boost::property_tree::ptree_error const& e) {
      std::cout << e.what() << '\n';
      return 1;
   }

   std::cout << "testval is " << testval << '\n';
   return 0;
}

And test.ini is:

[foo]
;bar = 2

Upvotes: 0

Views: 1723

Answers (2)

Micha&#235;l Roy
Micha&#235;l Roy

Reputation: 6487

I think you are confused about the use of default values.

As is now: If you change the value of foo.bar to 1 before reading the file, reading the file will overwrite foo.bar to the contents read from the file. If you comment out bar=2 in the ini file, foo.bar has no value.

If you change the value of put to 1 after read_ini, it is normal that the value from that point on is 1. put() sets the value of foo.bar to 1.

If what you want is set a default value for get() to return when foo.bar is not defined, you specify the default value in the call to get() as in:

testval = pt.get<int>("foo.bar", 1);  // gets foo.bar from pt, or 1 if not found.

You can omit the <int> type in 2 parameters calls to get(), since that gives it a type to work with, so this is equivalent to the call above:

testval = pt.get("foo.bar", 1); 

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249652

As per the documentation for read_ini():

Clears existing contents of property tree. In case of error the property tree unmodified.

So whatever you do beforehand doesn't matter.

Upvotes: 2

Related Questions