幾天前,在CSDN論壇看到這么一則討論: 在宏定義中怎么使用可變參數(shù)? ( http://expert.csdn.net/Expert/topic/2925/2925165.xml )。樓主希望能定義這樣的macro:
#define fun1(a, b, ...)?? fun2(__FILE__, __LINE__, a, b, ...)
我猜樓主是想寫trace,如果不能使用可變參數(shù)的macro,那么就得像MFC那樣寫一堆TRACE macros:
// 取自 MFC 7.1 的 afx.h
// The following trace macros are provided for
backward compatiblity
//? (they also take a fixed number of parameters which provides
//?? some amount of extra error checking)
#define TRACE0(sz)???????????????TRACE(_T("%s"), _T(sz))
#define TRACE1(sz, p1)????????? ?TRACE(_T(sz), p1)
#define TRACE2(sz, p1, p2)????? ?TRACE(_T(sz), p1, p2)
#define TRACE3(sz, p1, p2, p3)? ?TRACE(_T(sz), p1, p2, p3)
太丑陋了!還好,C99標(biāo)準(zhǔn)支持Variadic Macros,在GCC中,可以這么寫:
//
http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html
#define debug(format, ...)? fprintf(stderr, format, __VA_ARGS__)
還可以順便打印文件名和行號:
#define debug(format, ...)? do {\
??????????????? fprintf(stderr, "%s (%d): ", __FILE__, __LINE__);\
??????????????? fprintf(stderr, format, __VA_ARGS__);\
??????????????? } while (0)
但可惜Visual C++ 7.1還不支持這項功能:( 不過我們在C++中至少可以繞彎解決,做到 既能自動記錄文件名和行號,又能使用變長參數(shù)調(diào)用 。這個辦法不是我獨創(chuàng)的,實際上ATL的 atltrace.h 中就有它的實現(xiàn)( CtraceFileAndLineInfo class),我在Code Project也找到了相同的實現(xiàn)( http://www.codeproject.com/debug/location_trace.asp ),甚至在CUJ的C++ Experts Forum 也能看到相近的做法( http://www.cuj.com/documents/s=8250/cujcexp2106alexandr/ ),當(dāng)然Alexandrescu的辦法技巧性更強(qiáng)。
思路:寫一個重載了 operator() 的class,令 TRACE 宏返回該class的一個object:
#include
#include
#ifndef NDEBUG? // debug mode
class tracer
{
public:
? tracer(const char* file, int line)
??? : file_(file), line_(line)
? {}
?
? void
operator()
(
const char* fmt,
...
)
? {
??? va_list ap;
???
??? // print the file name and line number
??? fprintf(stderr, "%s (%d): ", file_, line_);
???
??? va_start(ap, fmt);
??? vfprintf(stderr, fmt, ap);
??? va_end(ap);
???
??? fprintf(stderr, "\r\n"); // print the new-line character
? }
private:
? // copy-ctor and operator=
? tracer(const tracer&);
? tracer& operator=(const tracer&);
private:
? const char* file_;
? int???????? line_;
};
#define TRACE (tracer(__FILE__, __LINE__))
#else? // NDEBUG
#define TRACE (void)
#endif // NDEBUG
int main()
{
#ifndef NDEBUG
? tracer(__FILE__, __LINE__)("%x", 123);
#endif
? TRACE("%s", "Happy debugging.");
}
這樣做是multithreading-safe的。G++ 3.3.1 / Visual C++ 7.1 / Borland C++ 5.5.1 通過。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=565
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
