我创建了一个模板但出现错误。
模板和主体(此代码在一个 cpp 文件中):
#include <iostream>
using namespace std;
template<class T>
void swap(T& x, T& y);
template<class T>
void swap(T& x, T& y){
T temp = x;
x = y;
y = temp;
}
int main(){
int n1 = 10, n2 = 5;
cout << "number before swap: num1= " << n1 << " num2= " << n2 << endl;
swap(n1, n2);//compilation error
cout << "number after swap: num1= " << n1 << " num2= " << n2 << endl;
system("pause");
return 0;
}
错误:
Error 1 error C2668: 'std::swap' : ambiguous call to overloaded function
c:\projects\template\main.cpp 42 1 Template
2 IntelliSense: more than one instance of overloaded function "swap"
matches the argument list:
function template "void swap(T &x, T &y)"
function template "void std::swap(_Ty &, _Ty &)"
argument types are: (int, int) c:\Projects\Template\main.cpp 43
2 Template
我不明白为什么会出现错误,因为一切看起来都很好。 感谢您的帮助。
谢谢。
最佳答案
您正在使用 using namespace std;
。因此,编译器无法知道行 swap(n1, n2);
是否意味着使用 std::swap
或您的自定义 swap
。您可以通过显式指定要使用的 namespace 来解决歧义。您可以使用 ::
指定全局命名空间,这是您定义 swap
函数的地方。尝试:
int main()
{
int n1 = 10, n2 = 5;
cout << "number before swap: num1= " << n1 << " num2= " << n2 << endl;
::swap(n1, n2);
cout << "number after swap: num1= " << n1 << " num2= " << n2 << endl;
return 0;
}
但是,这里真正的解决方案是删除 using namespace std;
。参见 here解释为什么这是一种不好的做法。
关于c++ - 当我创建一个模板时,我尝试使用它但是得到一个错误(C2668)和 IntelliSense 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43810968/