Template or Macro

Started by
9 comments, last by King Mir 9 years ago

Prefer templates over macros when both are usable, because templates offer better type safety and interact more intuatively with other language features. For example, safe delete could be written as a template in such a way that you get a compiler error when you try to delete an int, but you can't do that with a macro.

I veiw it as a hiarchy of tools for code reuse. It goes roughly as follows:

1) loops

2) functions

3) templates

4) macros

You use a loop when you need to do the same operation, for different values in sequence

You use a function when you need to do the same operation, for different values out of sequence

You use a template function when you need to do the same operation, for different values of different types.

You use a Macro when you need to do the same operation, but there are differences in structure.

(Polymoric classes could also fit in this hiarchy, between functions and templates)

There are other uses of macros too where templates obviously cannot be used.

This topic is closed to new replies.

Advertisement