Question

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"?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top