From some slides about template specialization:
#include <iostream>
using namespace std;
template<class X>
X& min(X& a, X& b)
{
return a > b ? b : a;
}
int& min(int& a, int & b)
{
// rewrite of the function in the case of int:
cout << "int explicit function\n";
return a > b ? b : a;
}
/*
new syntax – the more appropriate way:
template<>
int& min<int>(int& a, int& b)
{
cout << "int explicit function\n";
return a > b ? b : a;
}
*/
Why is the second way more "appropriate"?
The overload works fine for most of the contexts, and AFAIK is the suggested baseline approach. (see GOTW suggested by juanchopanza )
The difference hits if someone explicitly asks for the template, calling min<int>(x, y)
. In that case overloads are ignored and only the template (base or specialized) are considered.
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