来自一些关于模板特化的幻灯片:
#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;
}
*/
为什么第二种方式更“合适”?
最佳答案
重载适用于大多数上下文,AFAIK 是建议的基线方法。 (参见 juanchopanza 建议的 GOTW)
如果有人明确要求模板,调用 min<int>(x, y)
,差异就会出现。 .在这种情况下,重载将被忽略,仅考虑模板(基本或专用)。
关于c++ - 模板函数特化与重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17344405/