template <class T>
void max (T &a ,T &b)
{}//generic template #1
template<> void max(char &c, char &d)
{} //template specializtion #2
void max (char &c, char &d)
{}//ordinary function #3
what is difference between 1 ,2, and 3?
Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:
66) Don't specialize function templates
Function template specializations never participate in overloading: Therefore, any specializations you write will not affect which template gets used, and this runs counter to what most people would intuitively expect. After all, if you had written a nontemplate function with the identical signature instead of a function template specialization, the nontemplate function would always be selected because it's always considered to be a better match than a template.
The book advises you to add a level of indirection by implementing the function template in terms of a class template:
#include <algorithm>
template<typename T>
struct max_implementation
{
T& operator() (T& a, T& b)
{
return std::max(a, b);
}
};
template<typename T>
T& max(T& a, T& b)
{
return max_implementation<T>()(a, b);
}
See also:
The matching rules for template parameters subtly differ from that of overloaded functions. An example of what differs can be seen when you try to invoke max()
with arguments of different tyoes:
max(1,'2');
This will match the overloaded function, but neither the base template nor the specialization.
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