开发者

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 corresp开发者_如何学Conding benefits.


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; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜