///////////////////////////////////////////////// // MT3Q1.cpp - Tracer // // // // Jim Fawcett, CSE687 - Midterm, Spring 2010 // ///////////////////////////////////////////////// #include #include #include class tracer : private std::ostringstream // Made private as ostringstream { // doesn't provide virtual functions public: // so won't support polymorphism. tracer(const std::string& name) { *this << "\nstarting: " << (name_ = name); log.append(this->std::ostringstream::str()); this->std::ostringstream::str(""); } ~tracer() { *this << "\nending: " << name_; log.append(this->std::ostringstream::str()); } template tracer& operator<<(const T& t) { std::ostringstream& rStr = *this; rStr << t; log.append(this->std::ostringstream::str()); this->std::ostringstream::str(""); return *this; } std::string& str() { return log; } private: static std::string log; std::string name_; }; std::string tracer::log = ""; std::ostream& operator<<(std::ostream& out, tracer& tr) { out << tr.str().c_str(); return out; } void fun2(const std::string& say) { tracer t("fun2"); t << "\n argument = " << say; } void fun1() { tracer t("fun1"); std::string s = "my local string"; int count = 3; t << "\n " << s << ", my count = " << count; fun2("hello cse687"); } class global // created this global object so we { // see main's exit public: global() : t_("global") {} // here's where we show log ~global() { std::cout << t_ << "\n\n"; } private: tracer t_; } glob; void main() { std::cout << "\n MT3Q1 - Tracer"; std::cout << "\n ================"; tracer t("main"); fun1(); // uncomment if you decide not to use global tracer // std::cout << t << "\n\n"; }