From: stephan b. <st...@s1...> - 2004-12-31 22:44:13
|
Yo! One of the most interesting tricks serialization gives is the ability to "cast" between "similar" types. For example, casting a list<int> to a vector<double *>. Here's a demonstration showing how to convert a SimplePropertyStore to or from a std::map<string,string>: First we have to tell s11n to use a proxy for map<string,string> which is compatible with the proxy for SimplePropertyStore. i happen to know which proxy SPS uses, so we can use the same one. We do that with this registration code (called from our client app): #define PS11N_TYPE std::map<std::string,std::string> #define PS11N_TYPE_NAME "map" #define \ PS11N_SERIALIZE_FUNCTOR \ ::P::s11n::map::streamable_map_serializable_proxy #include <pclasses/SIO/RegisterSerializable.h> SPS is mostly std::map compliant, and uses that same proxy: see src/SIO/Proxy/SimplePropertyStore_s11n.h Yes, the exact same proxy can de/serialize both SPS and a std::map (and a std::multimap... *any* map-compliant type... even maps of maps of maps of pointers to maps). Now we create a SPS: SimplePropertyStore m; m["fred"] = "wilma"; m["barney"] = "betty"; m["days_in_december"] = 31; m["days_in_february"] = 28.5; m["the_letter_a"] = 'a'; save( m, std::cout ); And cast it to a std::map: typedef std::map<std::string,std::string> OtherMap; OtherMap m2; if( ! s11nCast( m, m2 ) ) { CERR << "Map conversion failed!\n"; return 1; } save( m2, std::cout ); Outputs: <!DOCTYPE s11n::io::expat_serializer> <s11n_node class="P::Util::SimplePropertyStore"> <barney>betty</barney> <days_in_december>31</days_in_december> <days_in_february>28.500000</days_in_february> <fred>wilma</fred> <the_letter_a>a</the_letter_a> </s11n_node> SimplePropertyStoreTest.cpp:54 : s11nCast() to map<string,string>: <!DOCTYPE s11n::io::expat_serializer> <s11n_node class="map"> <barney>betty</barney> <days_in_december>31</days_in_december> <days_in_february>28.500000</days_in_february> <fred>wilma</fred> <the_letter_a>a</the_letter_a> </s11n_node> This type of casting essentially works for any types which use "compatible" de/serialization algos. That means, they use algos which structure their serialized data identically. -- ----- st...@s1... http://s11n.net "...pleasure is a grace and is not obedient to the commands of the will." -- Alan W. Watts |