当我创建模板时,我会尝试使用它,但会出现错误(C2668)和Intellisense错误
When I create a template I try to use it but get an error(C2668) and IntelliSense error
我创建一个模板,但获取错误。
模板和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 是对病例敏感的,因此可以避免冲突,因此避免了歧义。但是,最好使用标准库版本。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- 当我创建模板时,我会尝试使用它,但会出现错误(C2668)和Intellisense错误
- 使用Kinect,错误C2668:对过载函数的模棱两可
- 日志(PCTSTR 格式,..)和日志(PCTSTR 文本):错误 C2668 对重载函数的不明确调用
- 从 VS2008 移植到 VS2013 时绑定中出现错误 C2668
- 错误C2668从站点对重载函数代码的调用不明确http://h264bitstream.sourceforge.net/
- 获取:错误 C2668:'sqrt':对重载函数的不明确调用