In many ways, templates work like preprocessor macros, replacing the templated variable with the given type. However, there are many differences between a macro like this:
#define min(i, j) (((i) < (j)) ? (i) : (j))
and a template:
template<class T> T min (T i, T j) { return ((i < j) ? i : j) }
Here are some problems with the macro:
- There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.
- The
iandjparameters are evaluated twice. For example, if either parameter has a postincremented variable, the increment is performed two times. - Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
模板与宏的区别
本文探讨了C++中模板与预处理器宏之间的区别。虽然两者都能实现类型参数化的效果,但模板提供了更强大的类型检查和错误报告功能。文章指出宏存在的几个问题:缺乏类型验证、参数重复计算以及错误消息不易理解等。
56

被折叠的 条评论
为什么被折叠?



