且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将函数转换为宏

更新时间:2023-02-16 21:18:12

为什么宏是好的?



1.避免重复打字(减少出错的风险)。



示例:因此,MFC,boost和ATL / WTL使用宏。



2.使用完全不同的行为来编写现有代码。



示例:模拟测试设施;交换新的定义和删除堆调试。



3.生成代码 - 源代码不适合手工编辑。



为什么宏不好?



1.对调试产生不利影响。

a。单步通过宏扩展到十几行。

b。在宏定义上设置一个断点。



2.隐藏 - 宏可以隐藏你的东西 - 使调试和代码审查更加困难。



示例:#define true false



3.欺骗现有代码,使用截然不同的行为进行编译。



4.宏不限于命名空间。



返回当天 - 内联函数之前 - 定义的函数作为一个宏是一种内联代码而不是普通函数调用的方法。使用__inline关键字,这个宏的使用已经过时。



摘要



仅使用宏如果绝对需要并且只有在没有其他机制的情况下。相反,对类型和常量/文字使用const,enum和typedef。



您将函数重写为宏的兴趣作为学习练习具有很大的价值但没有更多。一旦你开始使用其他宏定义宏,你也会发现一些惊喜。



完成学习宏之后,你最终可以使用C ++模板 - 这是比宏更强大 - 但可以限制在命名空间。



祝你好运。
Why macros are good?

1. avoid repetitive typing (less risk of mistakes).

Examples: MFC, boost and ATL/WTL use macros for this reason.

2. trick existing code to be compiled with wildly different behavior.

Examples: Mock facilities for testing; swapping out definitions of new and delete for heap debugging.

3. generated code - source code not meant for hand-editing.

Why macros are bad?

1. Adversely impacts debugging.
a. single-step through a macro that expands to a dozen lines.
b. set a break point on a macro definition.

2. Hiding - macros can hide things from you - to make debugging and code review more difficult.

Example: #define true false

3. Trick existing code to be compiled with wildly different behavior.

4. Macros are not confined to a namespace.

Back in the day - before inline functions - a function defined as a macro was a way to have inline code instead of a plain function call. With the __inline keyword, this use of a macro is obsolete.

Summary

Use a macro only if absolutely needed and only if there is no other mechanism. Instead, use const, enum, and typedef for types and constants / literals.

Your interest in re-writing a function as a macro has much value as a learning exercise but no more. You will also find a few surprises once you start defining macros using other macros.

After you're done learning macros, you can eventually play with C++ templates - which are more more powerful than macros - but can be confined to a namespace.

Good luck.