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++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01