Given the following code:
#include <iostream>
using namespace std;
template<typename T> void Print(T t) {
cout << t << endl;
}
template<> void Print<int>(int t) {
cout << "int = " << t << endl;
}
void Print(int i) {
cout << "int2 = " << i << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Print(1.3);
Print("tese");
Print(2);
char c;
cin >> c;
return 0;
}
Why is the call Print(2) not ambiguous, but instead calling void Print(int i) ?
ps: Tested with bcc64.exe and cl.exe.
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.
Function overloading means using a single name and giving more functionality to it. Operator overloading means adding extra functionality for a certain operator. When an operator is overloaded, the operator has different meanings, which depend on the type of its operands.
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.
The main advantage of function overloading is that it improves code readability and allows code reusability. The use of function overloading is to save memory space, consistency, and readability. It speeds up the execution of the program. Code maintenance also becomes easy.
Section 13.3.3 of the standard, on choosing the best function for an overloading, explicitly states that given the choice between a templated and a non-templated function having the exact same argument list, the non-templated function is always a better fit than the templated one.
This is because non-template functions are first-class citizens. See this article by Herb Sutter or this SO post for details.
From Herb Sutter's article:
Nontemplate functions are first-class citizens. A plain old nontemplate function that matches the parameter types as well as any function template will be selected over an otherwise-just-as-good function template.
If there are no first-class citizens to choose from that are at least as good, then function base templates as the second-class citizens get consulted next. Which function base template gets selected depends on which matches best and is the "most specialized" (important note: this use of "specialized" oddly enough has nothing to do with template specializations; it's just an unfortunate colloquialism) according to a set of fairly arcane rules:
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