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 act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Template Function Overloading:The name of the function templates are the same but called with different arguments is known as function template overloading. If the function template is with the ordinary template, the name of the function remains the same but the number of parameters differs.
Function partial specialization is not yet allowed as per the standard. In the example, you are actually overloading & not specializing the max<T1,T2> function. In the case of a function templates, only full specialization is allowed by the C++ standard, -- excluding the compiler extensions!
According to this article from Herb Sutter, one should always pick Class Specializing over Function Overload and definitely over Specialized Function Templates.
The reason is that
I must admit that before I read the article I have banged my head against the wall a few times. Why isn’t he picking my specialized function …
After reading the article I’ve never used Specialized Function Templates again.
Example:
template <class T> void foo( T t);
We should write foo like this so we can specialize it with class templates instead of function specializing.
template<class T>
struct FooImpl;
template <class T> void foo( T t) {
FooImpl<T>::foo(t);
}
Now we can specialze the template and don’t have to worry about the overload rules and we can even partitial specialize the template like this:
template<class U, class V>
struct FooImpl< QMap< U, V > >;
It seems that the StackOverflow members prefer Specialized Function Templates?
Why?
Because the Specialized Function Templates get a lot more upvotes than the Overload Solutions and the Class Specializing.
With the information that i have at the moment i find it perverse because i know that i can get it right, but i know that the one who comes after me will hit the wall.
There are already some links to the GOTWCA article so you must have read the article. This means that upvoters must have some extra information, please stand up and enlighten me.
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