In books on C++, why are we taught to use function overloading when we have templates at our disposal in C++?
Wouldn't it be better to show the effective (and correct) use of templates? As opposed to where function overloading is taught in most books on C++?
Or, are there good reasons to use one instead of the other?
What is the difference between function overloading and templates? Both function overloading and templates are examples of polymorphism features of OOP. Function overloading is used when multiple functions do quite similar (not identical) operations, templates are used when multiple functions do identical operations.
Function overloading is used when multiple functions do similar operations; templates are used when multiple functions do identical operations. Templates provide an advantage when you want to perform the same action on types that can be different.
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
Function Template is the correct terminology (a template to instantiate functions from). Template Function is a colloquial synonym. So, there's no difference whatsoever.
Templates provide an advantage when you want to perform the same action on types that can be different. A simple example:
template <typename T> T foo(const T& a, const T& b) { return a + b; }
You can use overloading when you want to apply different operations depending on the type:
struct Foo{ void foo() const {} }; void foo(int i) { std::cout << "i = " << i << "\n"; } void foo(const Foo& f) { f.foo(); }
You could achieve the above using templates and template specializations, but such specializations should represent a few exceptions to the general case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With