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