我在使这个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 -E我得到: #30&#34; macro_fun2.cpp&#34; int main(int argc,char * argv []) { CBMonitorDeviceRequest * ptr = new CBMonitorDeviceRequest; ptr-&gt; type = Monitor; ptr-> dn = new char(strlen(&#34; 1234&#34;)+ 1); strcpy(ptr-> dn,&#34; 1234&#34;); #45&#34; macro_fun2.cpp&#34; 开关(ptr-&GT;类型){ case MonitorID:{CBMonitor * pthis = static_cast(ptr); if(pthis&amp;&amp; strcmp(pthis-&gt; dn,&#34; 1234&#34;)== 0)Monitor = Query; else Monitor = Snapshot; 打破; }; }
返回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 :(得分:1)
我认为您需要CB##id
,而不是CBid##
。
答案 1 :(得分:0)
id##ID
将扩展为MonitorID
,未定义。您要么在Monitor
的定义中将MonitorID
重命名为rqtypes
,要么将其更改为id
。
CB##id
将扩展为CBMonitor
,这也未定义。您要么将class CBMonitorDeviceRequest
重命名为class CBMonitor
,要么将其更改为CB##id##DeviceRequest
。
除此之外,我看不出任何明显的问题。当然,除了内存泄漏。为什么不使用std::string
作为字符串?