Differences Between Templates And Macros
- Macros are not type safe; that is, a macro defined for integer operations cannot accept float data. They are expanded with no type checking.
- It is difficult to find error in macros.
- In case a variable is post-incremented or decremented, the operation is carried out twice.
Consider the following macro:
The macro defined in the above macro definition is expanded twice. Hence, it is a serious limitation of macros. The limitation of this program can be removed using a template as shown below.
Explanation: In the above program, the template function max() is defined. An integer value is passed to this function. The function max() increments the value and returns it.