2017-06-10 27 views
1

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

上面的代码编译无错误。

有人能解释一下吗?

我哪里错了?

+2

当你已经有一个'std :: max'时,你为什么要命名你的函数'max'?这很可能是你麻烦的原因。 – PaulMcKenzie

+0

我意识到我的错误。得到它了!谢谢! – manjula

+0

案例2工作的原因是,如果您有一个模板和一个普通函数都能很好地匹配所有参数,那么非模板将赢得重载解析。这有一个特定的平局规则。 –

回答

6

有一个std::max这是你与谁冲突。你的代码中是否有using namespace std;using std::max

使用不同数量的参数重载模板函数应该可以工作。

+0

是的,我在代码中使用'namespace std'。 – manjula

+3

@manjula那里你去,拿出来看看会发生什么,试着用'std :: cout'缩小'',使用std :: string'等等。将全局代码保存在代码中并不是一个好习惯。 – Curious

+0

@manjula也见https://stackoverflow.com/questions/44093351/is-using-namespace-foo-useless – Curious