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

Function overloading doesn't work with templates in C++?

本文关键字:C++ 重载 不适用 适用于 函数      更新时间:2023-10-16

我正在学习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

使用不同数量的参数重载模板函数应该有效。