--- custom_data_type.cpp.orig 2009-11-26 21:16:38.000000000 +0100 +++ custom_data_type.cpp 2009-11-26 22:00:42.000000000 +0100 @@ -14,35 +14,28 @@ // container (instead of std::string that standard ptree has). #include -#include -#include -#include -#include #include #include #include #include // Custom translator that works with boost::any instead of std::string -struct my_translator +template +struct variant_translator { + typedef Ext external_type; + typedef Int internal_type; - // Custom extractor - converts data from boost::any to T - template - bool get_value(const Ptree &pt, T &value) const + external_type + get_value(const internal_type &value) const { - value = boost::any_cast(pt.data()); - return true; // Success + return boost::any_cast(value); } - - // Custom inserter - converts data from T to boost::any - template - bool put_value(Ptree &pt, const T &value) const + internal_type + put_value(const external_type &value) const { - pt.data() = value; - return true; + return value; } - }; int main() @@ -51,30 +44,45 @@ using namespace boost::property_tree; // Property_tree with boost::any as data type - // Key comparison: std::less // Key type: std::string - // Path type: path // Data type: boost::any - // Translator type: my_translator - typedef basic_ptree, std::string, path, boost::any, my_translator> my_ptree; + // Key comparison: default (std::less) + typedef basic_ptree my_ptree; my_ptree pt; // Put/get int value - pt.put("int value", 3); - int int_value = pt.get("int value"); + typedef variant_translator int_tran; + pt.put("int value", 3, int_tran()); + int int_value = pt.get("int value", int_tran()); std::cout << "Int value: " << int_value << "\n"; // Put/get string value - pt.put("string value", "foo bar"); - std::string string_value = pt.get("string value"); + typedef variant_translator string_tran; + pt.put("string value", "foo bar", string_tran()); + std::string string_value = pt.get( + "string value" + , string_tran() + ); std::cout << "String value: " << string_value << "\n"; // Put/get list value + typedef std::list intlist; + typedef variant_translator intlist_tran; int list_data[] = { 1, 2, 3, 4, 5 }; - pt.put >("list value", std::list(list_data, list_data + sizeof(list_data) / sizeof(*list_data))); - std::list list_value = pt.get >("list value"); + pt.put( + "list value" + , intlist( + list_data + , list_data + sizeof(list_data) / sizeof(*list_data) + ) + , intlist_tran() + ); + intlist list_value = pt.get( + "list value" + , intlist_tran() + ); std::cout << "List value: "; - for (std::list::iterator it = list_value.begin(); it != list_value.end(); ++it) + for (intlist::iterator it = list_value.begin(); it != list_value.end(); ++it) std::cout << *it << ' '; std::cout << '\n'; }