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 over-ride the stream translator to change how Boolean values are parsed.
The problem is that on the input side of a property tree, there are users, and they can modify the configuration files. A Boolean value might be specified in a number of ways, like:
dosomething.enabled=true
dosomething.enabled=trUE
dosomething.enabled=yes
dosomething.enabled=ON
dosomething.enabled=1
The default behaviour is to check for 0 or 1 and then use
std::ios_base::boolalpha
to get the stream to try to parse the value in the appropriate manner for the current locale...which could be insane if we try to send a configuration file to international customers.
So what's the easiest way to override this behaviour or bool only? Not only easiest to implement, but easiest to use - so that the users of my class which derives from iptree don't need to do something special for Boolean values.
Thanks!
There is also a good example at theboostcpplibraries.com.
Based on that, I wrote for a custom parser (declaration omitted):
It's only for bool and std::string but easily extendable.
Then,
You can specialize
boost::property_tree::translator_between
so that a property tree will use a custom translator for abool
value type. This specialization must be visible (i.e.#includ
ed) by clients wanting the customized behavior. Here's a working example:test.json:
Output:
Please note that this example assumes that the property tree is case insensitive and uses
std::string
. If you wantBoolTranslator
to be more general, you'll have to makeBoolTranslator
a template and provide specializations for wide strings and case sensitive comparisons.