Skip to content

Instantly share code, notes, and snippets.

@607011
Created February 13, 2015 12:40
Show Gist options
  • Save 607011/6893a238c17e4ffa3707 to your computer and use it in GitHub Desktop.
Save 607011/6893a238c17e4ffa3707 to your computer and use it in GitHub Desktop.
BoolTranslator for boost::property_tree::ptree
#include <boost/algorithm/string/predicate.hpp>
struct BoolTranslator
{
typedef std::string internal_type;
typedef bool external_type;
// Converts a string to bool
boost::optional<external_type> get_value(const internal_type& str)
{
if (!str.empty()) {
if (boost::algorithm::iequals(str, "true") || boost::algorithm::iequals(str, "yes") || boost::algorithm::iequals(str, "enabled") || str == "1")
return boost::optional<external_type>(true);
else
return boost::optional<external_type>(false);
}
else
return boost::optional<external_type>(boost::none);
}
// Converts a bool to string
boost::optional<internal_type> put_value(const external_type& b)
{
return boost::optional<internal_type>(b ? "true" : "false");
}
};
// Specialize translator_between so that it uses our custom translator for
// bool value types. Specialization must be in boost::property_tree namespace.
namespace boost {
namespace property_tree {
template<typename Ch, typename Traits, typename Alloc>
struct translator_between<std::basic_string< Ch, Traits, Alloc >, bool>
{
typedef BoolTranslator type;
};
}
}
// taken from http://stackoverflow.com/questions/9745716/change-how-boostproperty-tree-reads-translates-strings-to-bool
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment