用于存储另一个宏然后恢复回来的临时宏
我希望对宏有更多的控制,例如断言(以及一些不直接受我控制的日志宏)。所以我决定做这样的事情,期望它能够工作(如果有人想知道,它不起作用的原因是 MY_ASSERT_COPY
的最后一个 undef
使 >MY_ASSERT
就在它之前)。
#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
现在我知道了几种解决方法,其中一种是为该文件的断言定义另一个宏,然后我可以将其关闭,而不会影响程序任何其他部分的断言。我最初认为这是一个非常优雅的解决方案(在我发现它无法编译之前),它允许我在任何地方使用 MY_ASSERT ,然后只需针对特定文件将其关闭。
由于上述方法不起作用,是否有一种解决方法可以让我有选择地终止宏而不影响周围的代码,并且无需定义另一个替代宏,例如 #define MY_ASSERT_FOR_VECTORS MY_ASSERT
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 allow 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一些编译器提供
#pragma push_macro
和#pragma pop_macro
来保存和恢复宏状态。但便携性有限。
Some compilers provide
#pragma push_macro
and#pragma pop_macro
to save and restore macro state.Limited portability though.
这可能并不适用于所有情况,但也许您可以简单地
undef
宏,根据需要定义它们,然后再次undef
它们。下次您的代码使用其中一些宏时,应该
#include
最初定义它们的头文件,以便再次定义这些宏。一种安全的选择是:
This may not work in all situations, but maybe you could simply
undef
the macros, define them as you wish and thenundef
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: