Rare cases where MACROs must be used(必须使用 MACRO 的极少数情况)
问题描述
调试宏可能需要很长时间.我们过得更好避免使用它们,除非在极少数情况下既不是常数,函数和模板都可以做我们想做的事情.
Debugging macros can take a lot of time. We are much better off avoiding them except in the very rare cases when neither constants, functions nor templates can do what we want.
什么是罕见的情况?
推荐答案
如果你想要真正的文本替换,那就是你使用宏的地方.看看 Boost.Preprocessor,这是在 C++03 中模拟可变参数模板的好方法,无需过多重复.
If you want actual textual replacement, that's where you use macros. Take a look at Boost.Preprocessor, it's a great way to simulate variadic templates in C++03 without repeating yourself too much.
换句话说,如果您想操作程序代码本身,请使用宏.
In other words, if you want to manipulate the program code itself, use macros.
另一个有用的应用是assert
,当NDEBUG
没有定义(通常是release模式编译)时,它被定义为无操作.
Another useful application is assert
, which is defined to be a no-op when NDEBUG
is not defined (usually release mode compilation).
这将我们带到下一点,这是第一个的特化:不同的代码具有不同的编译模式,或者在不同的编译器之间.如果你想要交叉编译器支持,你就离不开宏.总体上看一下 Boost,由于它必须支持的各种编译器的各种缺陷,它一直都需要宏.
That brings us to the next point, which is a specialization of the first one: Different code with different compilation modes, or between different compilers. If you want cross-compiler support, you can't get away without macros. Take a look at Boost in general, it needs macros all the time because of various deficiencies in various compilers it has to support.
另一个重要的点是当您需要调用站点信息而又不想给代码的用户带来错误时.您无法仅通过一个函数自动获得它.
Another important point is when you need call-site information without wanting to bug the user of your code. You have no way to automatically get that with just a function.
#define NEEDS_INFO()
has_info(__FILE__, __LINE__, __func__)
带有适当的 has_info
声明(和 C++11/C99 __func__
或类似的).
With a suitable declaration of has_info
(and C++11/C99 __func__
or similar).
这篇关于必须使用 MACRO 的极少数情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:必须使用 MACRO 的极少数情况


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01