Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ Macros To Check For Variable Existence

I am creating a logging facility for my library, and have made some nice macros such as:

#define DEBUG  myDebuggingClass(__FILE__, __FUNCTION__, __LINE__)
#define WARING myWarningClass(__FILE__, __FUNCTION__, __LINE__)

where myDebuggingClass and myWarningClass both have an overloaded << operator, and do some helpful things with log messages.

Now, I have some base class that users will be overloading called "Widget", and I would like to change these definitions to something more like:

#define DEBUG  myDebuggingClass(__FILE__, __FUNCTION__, __LINE__, this)
#define WARNING myWarningClass(__FILE__, __FUNCTION__, __LINE__, this)

so that when users call 'DEBUG << "Some Message"; ' I can check to see if the "this" argument dynamic_casts to a Widget, and if so I can do some useful things with that information, and if not then I can just ignore it. The only problem is that I would like users to be able to also issue DEBUG and WARNING messages from non-member functions, such as main(). However, given this simple macro, users will just get a compilation error because "this" will not be defined outside of class member functions.

The easiest solution is to just define separate WIDGET_DEBUG, WIDGET_WARNING, PLAIN_DEBUG, and PLAIN_WARNING macros and to document the differences to the users, but it would be really cool if there were a way to get around this. Has anyone seen any tricks for doing this sort of thing?

like image 203
rcv Avatar asked Jul 06 '10 21:07

rcv


1 Answers

Declare a global Widget* const widget_this = NULL; and a protected member variable widget_this in the Widget class, initialized to this, and do

#define DEBUG myDebuggingClass(__FILE__, __FUNCTION__, __LINE__, widget_this)

like image 164
Robert Cooper Avatar answered Oct 07 '22 09:10

Robert Cooper