简单Trace类实现
《C++沉思录》27章内容修改后所得:
1 /************************************************************************/ 2 /* Trace类,以及trace类输出重定向,C++沉思录27章 */ 3 /************************************************************************/ 4 #pragma once 5 #include <iostream> 6 using namespace std; 7 8 //打开/关闭trace输入输出流 9 static const int trace_debug = 1; 10 11 //输出流 12 class Channel 13 { 14 public: 15 Channel (ostream* o = &std::cout): trace_file(o){} 16 //重定向输出流 17 void Reset(ostream* o = &std::cout) 18 { 19 trace_file = o; 20 } 21 private: 22 friend class Trace; 23 template<class T> friend class Obj_trace; 24 ostream* trace_file; 25 }; 26 typedef CSingleton<Channel> TraceChannel; 27 28 class Trace 29 { 30 public: 31 Trace(const char* s,Channel* c = TraceChannel::Instance()) 32 { 33 if (trace_debug) 34 { 35 name = s; 36 cp = c;; 37 if (cp && cp->trace_file) 38 { 39 *cp->trace_file << "Trace begin : " << name << endl; 40 } 41 } 42 } 43 ~Trace() 44 { 45 if (trace_debug) 46 { 47 if (cp && cp->trace_file) 48 { 49 *cp->trace_file << "Trace end : " << name <<endl; 50 } 51 } 52 } 53 private: 54 Channel* cp; 55 const char* name; 56 }; 57 58 //传递类名给Obj_trace,可以作为待跟踪类的基类或成员变量存在 59 template<class T> 60 class Obj_trace 61 { 62 public: 63 Obj_trace(Channel* c = TraceChannel::Instance()) : ct(++count) 64 { 65 if (trace_debug) 66 { 67 cp = c; 68 if (cp && cp->trace_file) 69 { 70 *cp->trace_file << "Trace obj begin : " << typeid(T).name() << " "<< ct << " constructed" << endl; 71 } 72 } 73 } 74 ~Obj_trace() 75 { 76 if (trace_debug) 77 { 78 if (cp && cp->trace_file) 79 { 80 *cp->trace_file << "Trace obj end : " << typeid(T).name() << " "<< ct << " destoryed" << endl; 81 } 82 } 83 } 84 private: 85 Channel* cp; 86 const char* name; 87 static int count; 88 int ct; 89 }; 90 91 //每个不同的type类型都有唯一对应的count 92 template<class T> 93 int Obj_trace<T>::count = 0;