Temporary macro to store another macro and then reverting back
I want to have more control over macros such as assertions (and some logging macros that are not directly under my control). So I decided to do something like this, expecting it to work (in case somebody is wondering, the reason it does not work is that the last undef
of MY_ASSERT_COPY
invalidates MY_ASSERT
right before it).
#ifndef ENABLE_FULL_ERROR_ASSERTS
#define MY_ASSERT_COPY MY_ASSERT
#undef MY_ASSERT
#define MY_ASSERT
#endif
// Code for my current class, which happens to be header only
#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT MY_ASSERT_COPY
#undef MY_ASSERT_COPY
#endif
Now I know a few ways around it, one being to define another macro for assertions just for that file, which I can then turn off without affecting assertions in any other part of the program. I initially thought this was a really elegant solution (before I found out it did not compile) that will allow me to use MY_ASSERT
everywhere and then simply turn it off for particular files.
Since the above doesn't work, is there a workaround that will al开发者_如何转开发low me to selectively kill the macro without affecting the surrounding code and without defining another substitute macro like #define MY_ASSERT_FOR_VECTORS MY_ASSERT
Some compilers provide #pragma push_macro
and #pragma pop_macro
to save and restore macro state.
Limited portability though.
This may not work in all situations, but maybe you could simply undef
the macros, define them as you wish and then undef
them again.
The next time your code uses some of these macros it should #include
the header files where they were initially defined so it will define those macros again.
One safe option would be:
#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#define MY_ASSERT ....
#endif
// Code for my current class, which happens to be header only
#ifndef ENABLE_FULL_ERROR_ASSERTS
#undef MY_ASSERT
#include "headers.h" //etc
// line above should redefine the macros
#endif
精彩评论