当我创建模板时,我会尝试使用它,但会出现错误(C2668)和Intellisense错误

When I create a template I try to use it but get an error(C2668) and IntelliSense error

本文关键字:错误 C2668 Intellisense 建模 创建      更新时间:2023-10-16

我创建一个模板,但获取错误。

模板和main(一个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:projectstemplatemain.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:ProjectsTemplatemain.cpp   43  
2   Template

为什么我会出现错误,所以我不明白,因为一切都很好。感谢您的帮助。

谢谢。

您正在使用using namespace std;。因此,编译器无法知道行swap(n1, n2);是使用std::swap还是您的自定义swap。您可以通过明确指定要使用的名称空间来解决歧义。您可以使用::指定全局名称空间,这是您定义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;。请参阅此处的解释,说明这是一个不好的做法。

如果您必须具有using namespace std声明并实现自己的交换函数,则可以更改功能名称以从大写Swap()开始。由于C 是对病例敏感的,因此可以避免冲突,因此避免了歧义。但是,最好使用标准库版本。