c++ - 模板函数特化与重载

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

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

最佳答案

重载适用于大多数上下文,AFAIK 是建议的基线方法。 (参见 juanchopanza 建议的 GOTW)

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

关于c++ - 模板函数特化与重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17344405/

相关文章:

c++ - 在 C++ 中用枚举类型包装 C-API

c++ - 从文件逐行读入 vector<T> 对于二进制数据 C++ 不正确

java - 使用基类引用的派生类对象重载方法 - java

c# - 泛型类中的方法重载

C++:重载 = 运算符以创建 uint8_t 兼容数据类型

c++ - 避免对临时对象、右值析构函数进行不必要的分配

c++ - 错误 : declaration does not declare anything

c++ - 在 C++ 类中正确设计成员 setter/getter

c++ - 设计模式 : uniform interface for partially supported derived classes

python - 突出显示主动导航 : django 1. 4.2