문제

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