Alex Rivera | Logout

function overloading vs function templates - C++

Asked 2012-09-08T14:34:52.177
39

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?

Edit
Report

1 Answer

44

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.

answered 2012-09-08T14:39:08.733

Your Answer