Templates vs Macro. Who wins?

First let's find the smallest number using template:

template <typename T>
T findSmall(T x, T y)
{
    return (( x < y) ? x : y);
}
Above template returns result for below cases.
Only similar data types are handled by template
findSmall(4, 5) // int, int
findSmall(5.6, 7.5) // float, float
findSmall('c', 'z') // char, char

Now let's find the smallest number using macro:
#define findSmall(x, y) ((x < y) ? x : y)
Above macro returns result for below cases:
Even the dissimilar data types are also handled by macro.
findSmall(4, 5) // int, int
findSmall(5.6, 7.5) // float, float
findSmall('c', 'z') // char, char
findSmall(4, 5.6) // int, float
findSmall(5.6, 'c') // float, char

This does not mean macro is superior to template.

Comparison operation '<' can be overloaded in templates and dissimilar data types can be handled as well.

Comments

Popular posts from this blog

Compiler toolchains naming convention