模板函数专业化与重载

时间:2013-06-27 13:23:26

标签: 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;
}
*/

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

1 个答案:

答案 0 :(得分:1)

对于大多数情况,重载都可以正常工作,而AFAIK是建议的基线方法。 (见juanchopanza建议的GOTW

如果有人明确要求提供模板,请致电min<int>(x, y)。在这种情况下,忽略重载,只考虑模板(基础或专用)。