Templates vs. Macros

OverviewHow Do I

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 i and j parameters 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.