ckv
ckv

Reputation: 10820

Templates and function overloading

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

Answers (1)

Josh Haberman
Josh Haberman

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

Related Questions