function overloading vs function templates - C++

Templates cannot take varying numbers of arguments. Overloads can. In addition, a template indicates that you can operate on any data type, but it's pointless to represent this when in fact, the vast, vast majority of templates would be specializations only (in your system). Also, overloads can be virtual and template specializations cannot. Nor can specializations differ in their signatures from the base.

template<typename T> void foo(T& t);
template<> void foo<std::string>(std::string* ptr); // Illegal
void foo(std::string* ptr); // Legal

This would severely constrain what kinds of overload you could produce compared to the current system.


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.


You generally use templates when you want to do the same set of operations on many different data types.

You generally would use function overloading when you want to do different operations on certain sets of data.

the advantage of templates in a situation where you want to do the same set of operations on many different data types, is that the compiler will handle for you at compile time any possible new type you may create in the future that uses the templated function. if you were to use function overloading, you'd have to create a new function overload every time you created a new type that you wanted to pass to the specific function.