c++ - 当我创建一个模板时,我尝试使用它但是得到一个错误(C2668)和 IntelliSense 错误

标签 c++ templates

我创建了一个模板但出现错误。

模板和主体(此代码在一个 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/

相关文章:

C++ 参数化构造函数使代码在传递大输入时停止工作

c++ - 使用 c++ api 访问 cv::Mat 中的元素 (x,y)

c++ - std::pair 作为模板<class> 参数? C++

c++ - 如何为 std::unique_ptr 创建一个有效的 C++ 别名模板

C++ 使用运算符重载转换模板

templates - 如何在 dolibarr 上编辑 pdf 模板的页脚

c++ - 为什么空队列的大小在 pop 后会减一?

c++ - Qt中的单例类问题

c++ CopyFile函数问题

c++ - 在编译时是否需要短路评估规则?