Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function overloading vs function templates - C++

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?

like image 890
HalfWebDev Avatar asked Sep 08 '12 14:09

HalfWebDev


People also ask

What is the difference between function overloading and function template?

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.

What is the advantage of using a function template instead of overloaded functions?

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.

Can we have overloading of a function templates?

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.

What are the differences between function template and 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.


1 Answers

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.

like image 160
juanchopanza Avatar answered Oct 04 '22 14:10

juanchopanza