2012-09-28 107 views
0

我遇到問題使此COMPARE宏發揮作用。任何想法如何解決?預處理器字符串化宏不起作用

它的一個人造樣本 - 我想盡可能小。

#include <iostream> 
#include <string.h> 

enum rqtypes {Unknown, Monitor, Query, Snapshot }; 

class base { 
public: 
    base() : type(Unknown) {} 
    rqtypes type; 
}; 

class CBMonitorDeviceRequest : public base 
{ 
public: 
    CBMonitorDeviceRequest() : dn(0) {} 
    char* dn; 
}; 


//I want the equivalent of: 
//  case MonitorDeviceRequestID: 
//   CBMonitorDeviceRequest* pthis = static_cast<CBMonitorDeviceRequest*>(thisrq); 
//   if(pthis && strcmp(pthis->dn1, "1234") == 0) 
//    return 0; 
//   else 
//    return -1; 
//   break; 


int main(int argc, char* argv[]) 
{ 
    CBMonitorDeviceRequest* ptr = new CBMonitorDeviceRequest; 
    ptr->type = Monitor; 
    ptr->dn = new char(strlen("1234") + 1); 
    strcpy(ptr->dn, "1234"); 

#define COMPARE(id, thismsg) case id##ID: { \ 
    CB##id * pthis = static_cast<CB##id *>(thismsg); \ 
    if(pthis && strcmp(pthis->dn, "1234") == 0) \ 
     std::cout << "found"; \ 
    else \ 
     std::cout << "not found"; \ 
    break; } \ 

    switch(ptr->type){ 
     COMPARE(Monitor, ptr); 
    } 

#undef COMPARE 

    return 0; 
} 

我得到如:

(46) : error C2065: 'MonitorID' : undeclared identifier 
(46) : error C2051: case expression not constant 
(46) : error C2065: 'CBMonitor' : undeclared identifier 
(46) : error C2065: 'pthis' : undeclared identifier 
(46) : error C2061: syntax error : identifier 'CBMonitor' 
(46) : error C2065: 'pthis' : undeclared identifier 
(46) : error C2065: 'pthis' : undeclared identifier 
(46) : error C2227: left of '->dn' must point to class/struct/union/generic type 

使用GCC -EI得到: #30 「macro_fun2.cpp」 INT主(INT ARGC,CHAR *的argv []){ CBMonitorDeviceRequest * ptr = new CBMonitorDeviceRequest; ptr-> type = Monitor; ptr-> dn = new char(strlen(「1234」)+ 1); strcpy(ptr-> dn,「1234」); #45「macro_fun2.cpp」 switch(ptr-> type)case MonitorID:{CBMonitor * pthis = static_cast(ptr);如果(pthis & & strcmp(pthis-> dn,「1234」)== 0)Monitor = Query;其他監視器=快照; 休息; }; }

return 0; }

*** By the way I changed code to to avoid the massive printing of iostream by preprocessor - otherwise -E printing would have been huge. 

#define COMPARE(id, thismsg) case id##ID: { \ 
    CB##id * pthis = static_cast<CB##id *>(thismsg); \ 
    if(pthis && strcmp(pthis->dn, "1234") == 0) \ 
     id = Query; \ 
    else \ 
     id = Snapshot; \ 
    break; } \ 
+0

*問題*是什麼? – Puppy

+2

首先,字符串化操作符是一個'#',並且它不會出現在此代碼中的任何位置。 –

+0

我會建議你先做,只是預處理輸出,看看發生了什麼。如果您使用GCC,則可以使用-E選項完成。如果您仍然無法解決原因,請在此處粘貼預處理的輸出並讓我們知道。 http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Preprocessor-Options.html#Preprocessor-Options – Salgar

回答

0

id##ID將擴大到MonitorID,這是未定義的。您要麼將Monitor重命名爲MonitorID的定義爲rqtypes,要麼將其更改爲id

CB##id將擴大到CBMonitor,這也沒有定義。您要麼將class CBMonitorDeviceRequest重命名爲class CBMonitor,要麼將其更改爲CB##id##DeviceRequest

除此之外,我看不到任何明顯的問題。當然,除了內存泄漏之外。你爲什麼不使用std::string作爲你的字符串?

1

我想你想CB##id,不CBid##

+0

謝謝。然而,我也有我剛添加的錯誤。 –