///////////////////////////////////////////////////////////////// // serialize.cpp - defines serialization interface and class // // Exam3:Q1 // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 05 // ///////////////////////////////////////////////////////////////// #include #include #include #include ///////////////////////////////////////////////////////////////// // answer starts here template class persistent : public U { public: persistent() {} persistent(const U& u) : U(u) {} virtual ~persistent() {} virtual void serialize(std::ostream& os) = 0; virtual V deserialize(std::istream& is) = 0; }; class persistentString : public persistent { public: persistentString(const std::string& s) : persistent(s) {} virtual void serialize(std::ostream& os) { for(unsigned int i=0; iappend(1,is.get()); } return *this; } }; // end of answer ///////////////////////////////////////////////////////////// // The remaining code is here for my own amusement class persistentStringStream; template<> persistent ::persistent(const std::ostringstream& ss) { str(ss.str()); } class persistentStringStream : public persistent { public: persistentStringStream(const std::ostringstream& s) : persistent(s) {} persistentStringStream() {} persistentStringStream(const std::string& s) { static_cast(this)->str(s); } virtual void serialize(std::ostream& os) { std::string temp = this->str(); for(unsigned int i=0; iput(is.get()); } return *this; } }; // end of amusement ///////////////////////////////////////////////////////////// void main() { persistentString ps = "\n now is the hour"; std::ofstream out("temp.dat"); ps.serialize(std::cout); ps.serialize(out); out.close(); std::ifstream in("temp.dat"); ps.deserialize(in); std::cout << ps.c_str() << "\n\n"; in.close(); /////////////////////////////////////////////////////////// // more amusement follows persistentStringStream pss("\n persistentStringStream: "); pss.seekp(0,std::ios::end); pss << 15 << " " << 3.1415927; out.open("temp.dat"); pss.serialize(std::cout); pss.serialize(out); out.close(); in.open("temp.dat"); pss.deserialize(in); std::cout << pss.str().c_str() << "\n\n"; in.close(); }