agrippa1994

Serialization

Feb 19th, 2014
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include <boost/archive/text_iarchive.hpp>
  2. #include <boost/archive/text_oarchive.hpp>
  3. #include <boost/serialization/access.hpp>
  4. #include <boost/move/move.hpp>
  5.  
  6. #include <boost/thread.hpp>
  7.  
  8. #include <iostream>
  9. #include <string>
  10. #include <sstream>
  11.  
  12. typedef boost::archive::text_oarchive outputArchive;
  13. typedef boost::archive::text_iarchive inputArchive;
  14.  
  15. template<typename T> class serializableValue
  16. {
  17.     T _t;
  18. public:
  19.     serializableValue(T t) : _t(t) { }
  20.     serializableValue()  { }
  21.  
  22.     serializableValue(serializableValue &rhs) : _t(rhs._t) { }
  23.     serializableValue(serializableValue &&rhs) : _t(rhs._t) { }
  24.  
  25.     T operator ()() const { return _t; }
  26.  
  27.     void operator=(T &rhs) { _t = rhs; }
  28.     void operator=(T rhs)  { _t = rhs; }
  29.  
  30. private:
  31.     friend boost::serialization::access;
  32.  
  33.     template<typename U> void serialize(U & ar, const unsigned int)
  34.     {
  35.         ar & _t;
  36.     }
  37. };
  38.  
  39.  
  40. int main()
  41. {
  42.     for(;;)
  43.     {
  44.         std::string data;
  45.  
  46.         // Daten serialisieren
  47.         {
  48.             std::stringstream ss;
  49.             outputArchive oa(ss);
  50.  
  51.             oa << serializableValue<int>(5) << serializableValue<float>(5.5) << serializableValue<std::string>("Hallo Welt");
  52.  
  53.             std::cout << "Serialisierten Daten: " << ss.str() << std::endl;
  54.  
  55.             data = ss.str();
  56.         }
  57.  
  58.         // Daten deserialisieren
  59.         {
  60.             std::stringstream ss(data);
  61.             inputArchive ia(ss);
  62.  
  63.             serializableValue<int> x; serializableValue<float> y; serializableValue<std::string> z;
  64.             ia >> x >> y >> z;
  65.  
  66.  
  67.             std::cout << "Deserialisiert: " << x() << ' ' << y() << ' ' << z() << std::endl;
  68.         }
  69.     }
  70.    
  71.    
  72.  
  73.    
  74.     std::cin.get();
  75. }
Advertisement
Add Comment
Please, Sign In to add comment