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