【发布时间】:2017-11-04 07:59:18
【问题描述】:
我正在学习使用函数模板。我发现如果我将参数类型声明为引用,程序就会工作。但是如果参数类型不是引用,我会得到错误。例如:
下面的代码打印出正确的结果并且没有错误。
#include <iostream>
using namespace std;
template <typename T>
T & max (T & a, T & b){
return a>b?a:b;
}
int main(int argc, char const *argv[])
{
cout << max(1,2) << endl;
return 0;
}
但是如果我把代码中的“&”全部去掉,也就是把上面的程序改成如下:
#include <iostream>
using namespace std;
template <typename T>
T max (T a, T b){
return a>b?a:b;
}
int main(int argc, char const *argv[])
{
cout << max(1,2) << endl;
return 0;
}
此代码将导致以下错误。
a.cpp: In function ‘int main(int, const char**)’:
a.cpp:11:17: error: call of overloaded ‘max(int, int)’ is ambiguous
cout << max(1,2) << endl;
^
a.cpp:5:4: note: candidate: T max(T, T) [with T = int]
T max (T a, T b){
^~~
In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
from /usr/include/c++/7/ios:40,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from a.cpp:1:
/usr/include/c++/7/bits/stl_algobase.h:219:5: note: candidate: constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
为什么? 谢谢大家帮助我!
【问题讨论】:
-
编译器告诉你:你对 max 的调用是模棱两可的,我想是因为 std 命名空间中有 max 模板
-
不使用
using namespace std;的另一个理由 -
第一个示例无效,您没有使用模板。