好的,这是程序,绝对正确
#include <iostream>
using namespace std;
template <typename T>
void Swap(T &a , T &b);
int main(){
int i = 10;
int j = 20;
cout<<"i, j = " << i <<" , " <<j<<endl;
Swap(i,j);
cout<<"i, j = " << i <<" , " <<j<<endl;
}
template <typename T>
void Swap(T &a , T &b){
T temp;
temp = a ;
a = b;
b= temp;
}
但是当我将函数的名称从 Swap 更改为 swap 它产生一个错误说
error: call of overloaded 'swap(int&, int&)' is ambiguous| note: candidates are: void swap(T&, T&) [with T = int]| ||=== Build finished: 1 errors, 0 warnings ===|
发生了什么?使用模板以大写字母开头的函数启动规则是什么?
最佳答案
这是因为已经存在一个名为swap
的函数。它实际上位于 std
命名空间下,但是因为您有 using namespace std
行,所以它没有 std::
前缀。
如您所见,使用 using namespace std
并不总是一个好的选择,因为可能会发生名称冲突,如本例所示。一般来说,人们应该不喜欢使用 using
指令,除非有真正的原因 - 命名空间的存在是有原因的 - 以防止名称冲突。
关于c++ - 为什么我将函数命名为 `swap` 时会出现模板错误,但 `Swap` 没问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324636/