gpt4 book ai didi

c++ - 在不需要的宏使用上强制出现 C++ 错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:52 25 4
gpt4 key购买 nike

我有一个到处都用的宏

   #define DBG(s) do_something_with(s)

但是,在其中一个文件中,我想让它无法使用 - 并导致编译错误

#ifdef DBG
#undef DBG
#define DBG(s) #error "do not use DBG in this file"
#endif

显然,我的示例不起作用。对如何完成这样的事情有什么建议吗?

最佳答案

在 C++11 中,你可以这样做:

#ifdef DBG
# undef DBG
#endif
#define DBG(s) static_assert(false, "you should not use this macro")

错误信息如下:

C:/Code/Test/src/src/main.cpp: In function 'int main(int, char**)':
C:/Code/Test/src/src/main.cpp:38:16: error: static assertion failed: you should not use this macro
#define DBG(s) static_assert(false, "you should not use this macro")
^
C:/Code/Test/src/src/main.cpp:45:5: note: in expansion of macro 'DBG'
DBG(42);
^

在 C/C++03 中,一个简单的 #undef 将产生如下结果:

C:/Code/Test/src/src/main.cpp:45:11: error: 'DBG' was not declared in this scope

这可能就足够了。

关于c++ - 在不需要的宏使用上强制出现 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22013572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com