必须使用 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).
相关文章