简体   繁体   English

模板函数专业化与重载

[英]Template function specialization vs. overloading

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. 对于大多数情况,超载工作正常,AFAIK是建议的基线方法。 (see GOTW suggested by juanchopanza ) (参见juanchopanza建议的GOTW)

The difference hits if someone explicitly asks for the template, calling min<int>(x, y) . 如果有人明确要求输入模板,则调用min<int>(x, y) In that case overloads are ignored and only the template (base or specialized) are considered. 在这种情况下,忽略重载并且仅考虑模板(基础或专用)。

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

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