我正在學習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工作的原因是,如果您有一個模板和一個普通函數都能很好地匹配所有參數,那麼非模板將贏得重載解析。這有一個特定的平局規則。 –