繁体   English   中英

模板函数专业化与重载

[英]Template function specialization vs. overloading

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

#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) 在这种情况下,忽略重载并且仅考虑模板(基础或专用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM