宏的应用
今天粗略的看了下glog的源代码,发现一处是宏的替换应用,特提出来分享。
template<class Iter> inline void PrintSequence(std::ostream& out, Iter begin, Iter end) { using ::operator<<; // Output at most 100 elements -- appropriate if used for logging. for (int i = 0; begin != end && i < 100; ++i, ++begin) { if (i > 0) out << ' '; out << *begin; } if (begin != end) { out << " ..."; } }
#define OUTPUT_TWO_ARG_CONTAINER(Sequence) \ template<class T1, class T2> \ inline std::ostream& operator<<(std::ostream& out, \ const Sequence<T1, T2>& seq) { \ google::PrintSequence(out, seq.begin(), seq.end()); \ return out; \ }
OUTPUT_TWO_ARG_CONTAINER(std::vector)
OUTPUT_TWO_ARG_CONTAINER(std::deque)
OUTPUT_TWO_ARG_CONTAINER(std::list)
在此处宏的作用完全就是字符串替换了,替换完后,就#undef了。
#undef OUTPUT_TWO_ARG_CONTAINER
处理非常精妙。
细处只能去代码里体会。