/////////////////////////////////////////////////////////////////////// // oSockProto.cpp - helper demonstration for Project #3 // // Shows how to implement insertion operator for a socket handler // // derived from ostringstream that inserts into the socket in one // // invocation. // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 2004 // /////////////////////////////////////////////////////////////////////// #include #include #include /////////////////////////////////////////////////////////////////////// // class message - demonstrates sending user defined types to socket class message : public std::string { public: message(const std::string& s) : std::string( std::string("") + s + std::string("") ) {} }; // base class std::string provides: // ostream& operator<<(ostream&, const std::string&) // used in template oSockProto::operator<<(const T &t) /////////////////////////////////////////////////////////////////////// // class oSockProto demonstrates how to implement insertion // that sends to socket class oSockProto : private std::ostringstream { public: template oSockProto& operator<<(const T& t); private: void send(); }; //----< simulates sending to socket >---------------------------------- // // extract string from base and send // void oSockProto::send() { std::cout << this->str(); // in real class this will go to socket } //----< insertion operator >------------------------------------------- // // will accept any type that overloads operator<<, used with base class // template oSockProto& oSockProto::operator<<(const T &t) { std::ostringstream& base = *this; // get base part base << t; // convert t to string using ostringstream converters send(); // extract and send string str(""); // empty buffer for next input return *this; } // void main() { oSockProto osp; osp << "\n Simulate sending to socket " << "\n ============================\n"; // What goes into osp are a double, int, C string, and user-defined message. // What comes out, on cout, are four strings. // Conversions are compliments of your friendly ostringstream class. osp << "\n " << 3.1415927; osp << "\n " << 2; osp << "\n " << "now is the hour"; osp << "\n " << message("a message"); std::cout << "\n\n"; }