我被分配了更新舊項目的任務。我必須做的第一件事就是擴展現有的代碼以結合新的功能。作爲其中的一部分,我修改了現有的宏來打印傳入消息的JSON表示(通過CORBA,到C++結構中)。然後,我加入了boost program_options和一個新的記錄器,現在我想對這些宏進行現代化。將JSON記錄宏轉換爲模板函數...代碼中需要的參數名稱
問題是,我不知道如何實現我用模板做的宏。關鍵的問題是,我使用的參數爲宏的名稱來訪問該結構的字段:
//Defines the string that precedes the variable name in a JSON name-value pair (newline,indent,")
#define JSON_PRE_VNAME _T("%s,\n\t\t\t\t\"")
//Defines the string that follows the variable name in a JSON name-value pair (":) preceding the value
#define JSON_SEP _T("\":")
#define printHex(Y,X) _tprintf(_T("%02X"), (unsigned char)##Y->##X);
// ******** MACRO **********
// printParam (StructureFieldName=X, ParamType=Y)
// prints out a json key value pair.
// e.g. printParam(AgentId, %s) will print "AgentId":"3910"
// e.g. printParam(TempAgent, %d) will print "TempAgent":1
#define printParam(X,Y) if(strcmp(#Y,"%s")==0){\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T("\"%s\""),_logBuf,myEvent->##X);\
}else{\
_byteCount += _stprintf(_logBuf,JSON_PRE_VNAME _T(#X) JSON_SEP _T(#Y),_logBuf,myEvent->##X);\
}\
printBufToLog();
而且它使用的是這樣的:
//CORBA EVENT AS STRUCT "event"
else if(event.type == NI_eventSendInformationToHost){
evSendInformationToHost *myEvent;
event.data >>= myEvent; //demarshall
printParam(EventTime,%d);
printParam(Id,%d);
printParam(NodeId,%d);
}
,這導致JSON像這樣的:
「EVENTTIME」:1299239194, 「ID」:1234567, 「的NodeId」:3
等等
很顯然,我有評論這些宏還算不錯,但我希望爲別人着想看,有一個很好的方式來實現與模板相同的結果的代碼。我不得不說這些宏使得向消息記錄器添加新事件變得非常容易。
基本上我該怎麼做「#X」和帶模板的## X?
任何指針,將不勝感激。
謝謝!
第二個宏 – 6502 2011-03-04 20:33:50
@ 6502上缺少'}':已更正,謝謝! – 2011-03-06 00:23:16
感謝您的信息。這樣做()想法是一個很好的補充。 – Dennis 2011-03-07 08:25:20