c++ - 函数重载不适用于 C++ 中的模板?

标签 c++ templates overloading

我正在学习 C++,并且遇到了模板的用法。

所以我尝试使用如下模板实现以下两个功能:

template <typename T>
T max(T a, T b){
    return (a > b) ? a : b;
}

template <typename T>
T max(T a, T b, T c){
    return max( max(a, b), c);
}

好吧,上面的实现在编译过程中抛出了一些错误。

这是错误的样子:

templateEx.cpp:13:14: error: call to 'max' is ambiguous
        return max( max(a, b), c);
                    ^~~
templateEx.cpp:17:22: note: in instantiation of function template specialization
      'max<int>' requested here
        cout<<"2, 3, 4 : "<<max(2,3,4);
                            ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:2654:1: note: 
      candidate function [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
^
templateEx.cpp:7:3: note: candidate function [with T = int]
T max(T a, T b){
  ^
1 error generated.

但另一方面,如果我不使用任何模板,我使用普通函数重载,如下例所示:

int max(int a, int b){
    return (a > b) ? a : b;
}

int max(int a, int b, int c){
    return max( max(a, b), c);
}

以上代码编译无错误。

有人可以解释一下吗?

我哪里错了?

最佳答案

有一个std::max这就是你与之冲突的地方。您的代码中是否有using namespace std;using std::max

用不同数量的参数重载模板函数应该可行。

关于c++ - 函数重载不适用于 C++ 中的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469440/

相关文章:

c++ - CRTP 派生类方法的返回类型的转发

c++ - 可变参数模板(带有类和函数)编译失败

c++ - 矩阵类 C++ 作为 matlab 运算符重载

haskell - 为什么 Haskell 中的这种类型注释是必要的?

JAVA:具有相同名称的方法?

c++ - std::conditional 未被评估

c++ - 是否有用于检测 USB 过流的 Windows API?

templates - 在不编辑默认模板的情况下在 Magento 后端添加自定义仪表板 "box"的正确方法是什么?

c++ - 替换失败

c++ - 将 IO 寄存器作为模板参数传递