模板函数专业化与重载

nod*_*dwj 5 c++ templates overloading specialization template-function

从一些关于模板专业化的幻灯片:

#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;
}
*/
Run Code Online (Sandbox Code Playgroud)

为什么第二种方式更"合适"?

Bal*_*Pal 1

重载对于大多数情况都适用,并且 AFAIK 是建议的基线方法。(参见juanchopanza 建议的GOTW )

如果有人明确要求模板并调用min<int>(x, y). 在这种情况下,重载将被忽略,仅考虑模板(基本或专用)。