#include<iostream>
template <typename T>
void swap(T &a, T &b);
//template <typename T>
//void swap(T *a, T *b, int n);
void show(int * a);
const int Lim = 8;
int main() {
//using namespace std;
int i = 10;
int j = 20;
std::cout << "i, j= " << i << j << std::endl;
swap(i,i);
std::cout << "swap int: i,j = " << i << j << std::endl;
/*
int d1[Lim] = {0,4,0,7,0,4,0,7};
int d2[Lim] = {0,7,2,0,0,4,0,7};
show(d1);
show(d2);
swap(d1, d2, 2);
cout << "after swap: " << endl;
show(d1);
show(d2);
*/
return 0;
}
template <typename T>
void swap(T &a, T &b) {
T temp;
temp = a;
a= b;
b= temp;
}
/*
template <typename T>
void swap(T *a, T *b, int n) {
for(int i = 0; i < n; i++) {
T temp;
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
*/
void show(int *a) {
using namespace std;
for(int i = 0;i < Lim; i++) {
cout << a[i];
}
}
代码如上,是一个简单的模板的demo,但是编译不过,会报错:
error: call of overloaded ‘swap(int&, int&)’ is ambiguous
15 | swap(i,i);
| ^
看了一个小时,不知道哪里有问题,终于在一个博客下面找到了答案:
因为使用了using namespace std;
这个里面有同名函数swap,所以会报错。
去掉using namespace std;
改用std::即可。