Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top