我正在学习C++,并且我遇到了模板的用法。函数重载不适用于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'时,你为什么要命名你的函数'max'?这很可能是你麻烦的原因。 – PaulMcKenzie
我意识到我的错误。得到它了!谢谢! – manjula
案例2工作的原因是,如果您有一个模板和一个普通函数都能很好地匹配所有参数,那么非模板将赢得重载解析。这有一个特定的平局规则。 –