[lug] simple iostream bug?
Tkil
tkil at scrye.com
Thu Mar 14 17:28:51 MST 2002
>>>>> "DS" == D Stimits <stimits at idcomm.com> writes:
DS> Basically it is just a function to take a reference to an ostream,
DS> insert some text, and return it by reference. In this case it is
DS> cout.
a more c++ish idiom (at least to my eyes) would be to create an
object, and then print the object (using "<<") onto the output stream.
there's a nice idiom for making "<<" behave polymorphically, as well:
| #include <iostream>
| using std::cout;
|
| #include <iomanip>
| using std::endl;
|
| #include <string>
| using std::string;
|
| class HTTPHeader {
| private:
| int status_code_;
| string content_type_;
| public:
| HTTPHeader(int status_code,
| const string & content_type)
| : status_code_(status_code),
| content_type_(content_type)
| {}
|
| virtual ostream & print_to_ostream(ostream & os) const;
| static string status_text(int status_code);
| };
|
| ostream &
| HTTPHeader::print_to_ostream(ostream & os) const
| {
| return os << status_code_ << " " << status_text(status_code_) << endl
| << "Content-type: " << content_type_ << endl;
| }
|
| string
| HTTPHeader::status_text(int status_code)
| {
| switch (status_code)
| {
| case 200: return "Ok";
| default: return "Unknown Status";
| }
| }
|
| ostream &
| operator << (ostream & os, const HTTPHeader & h)
| {
| return h.print_to_ostream(os);
| }
|
| int main(int argc, char * argv [])
| {
| HTTPHeader header(200, "text/html");
|
| cout << header << endl
| << "<html>" << endl
| << " <head><title>test</title</head>" << endl
| << " <body><p>foo</p</body>" << endl
| << "</html>" << endl;
|
| return 0;
| }
More information about the LUG
mailing list