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 的极少数情况
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
