Reputation: 10820
If funciton overloading and templates serve more the less the same purpose then which one should we go for templates or function overloading and what are the corresponding benefits.
Upvotes: 2
Views: 271
Reputation: 4210
With overloaded functions, you have to explicitly write out each overload:
int max(int x, int y) { return x > y ? x : y; }
long max(long x, long y) { return x > y ? x : y; }
char max(char x, char y) { return x > y ? x : y; }
// etc.
This is tedious, but can be beneficial if the function body needs to be different based on the type.
Templates are nice when the same source code can be used for any type. You specify the pattern, and the compiler generates the expansions as needed:
// Can be used with any type that supports ">".
template<typename T> T max(T x, T y) { return x > y ? x : y; }
Upvotes: 6