I am having a problem getting this COMPARE macro to work. Any ideas on how to fix?
Its a bit of an artificial sample – I wanted to make it as small as possible.
#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;
}
I get eg:
(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
Using gcc -E I get:
# 30 “macro_fun2.cpp”
int main(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); if(pthis && strcmp(pthis->dn, “1234”) == 0) Monitor = Query; else Monitor = Snapshot;
break; };
}
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; } \
id##IDwill expand toMonitorID, which isn’t defined. You either want to renameMonitortoMonitorIDin the definition ofrqtypes, or change this to justid.CB##idwill expand toCBMonitor, which also isn’t defined. You either want to renameclass CBMonitorDeviceRequesttoclass CBMonitor, or change this toCB##id##DeviceRequest.Apart from that, I can’t see any obvious problems. Apart from the memory leak, of course. Why aren’t you using
std::stringfor your strings?