少数情况下,宏必须使用 [英] Rare cases where MACROs must be used

查看:136
本文介绍了少数情况下,宏必须使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调试宏可能需要大量的时间。我们要好得多
  避免他们除了在非常罕见的情况下,当没有常数,
  函数模板也可以做我们想做的。

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.

什么是罕见的情况下?

推荐答案

如果你想实际的文本替换,这就是你使用宏。看看加速。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.

在换句话说,如果你想 操纵程序code本身,使用宏。

In other words, if you want to manipulate the program code itself, use macros.

另外一个有用的应用是断言,其定义为,当 NDEBUG 没有定义无操作(通常发布模式编译)。

Another useful application is assert, which is defined to be a no-op when NDEBUG is not defined (usually release mode compilation).

这把我们带到下一个点,这是第一个的特化:不同的code用不同的编译方式,或不同的编译器之间。如果你想交叉编译器的支持,你不能脱身没有宏。看看一般升压,它需要因为它支持各种编译器的种种不足宏所有的时间。

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.

另外重要的一点是,当你需要的呼叫站点信息不希望错误的code的用户。你有没有办法自动获得与只是一个函数。

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).

这篇关于少数情况下,宏必须使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆