有宏的任何好的用途吗? [英] Are there any good uses of macros?
问题描述
据我所知,宏在编译器甚至看到它之前重新排列程序文本,从而潜在地导致问题。我几乎看不到他们在C ++代码,大多在C。
As far as I know, macros rearrange the program text before the compiler even sees it properly, thus potentially causing problems. I hardly ever see them in C++ code, mostly in C.
我知道的唯一的好用,是包含保护( #ifndef
)。
The only good use I know of, is inclusion guards (#ifndef
).
需要还有其他要做的宏,不能以更清晰的方式实现? / p>
Is there anything else that needs to be done with macros and cannot be implemented in a cleaner way?
推荐答案
记录和例外。
宏允许您轻松捕获 __ FILE __
, __ LINE __
和 __func __
。确保你可以每次手动编写它们,但坦率地说,这是单调乏味和容易出错( __ FILE __
和 __ func __
C字符串,所以你有风险混合起来)。
A macro allows you to effortlessly capture __FILE__
, __LINE__
and __func__
. Oh sure you could write them manually each time, but frankly this is tedious and error prone (both __FILE__
and __func__
are C-string so you risk mixing them up).
这篇关于有宏的任何好的用途吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!