如何解决我在使用void swap在C ++中对该函数进行模板化时是否做过任何巧合?
我当前正在使用C ++ 17,我想简化程序。但是,我被抛出错误:
more than one instance of overloaded function \"swap\" matches the argument list: -- function template \"void swap(T &a,T &b)\" -- function template \"std::enable_if<std::__and_<std::is_move_constructible<_Tp>,std::is_move_assignable<_Tp>>::value,void>::type std::swap(_Tp &__a,_Tp &__b)\" -- argument types are: (int,int)",
这是我写的代码:
#include <iostream>
#include <string>
using namesapce std;
template <typename T>
void swap(T &a,T &b) {
T temp = a; //Temporary copy to reuse
a = b;
b = temp;
}
int main() {
int x,y;
cin >> x >> y;
cout << "X: " << x << "\t Y: " << y << endl; //Tester
swap(x,y) //Where the error happened
cout << "New X: " << x << "\t New Y: " << y << endl; //Tester
string name1 = "FOO";
string name2 = "BAR";
swap(name1,name2);
cout << name1 << "\t" << name2 << endl;
return 0;
}
有趣的是,当我调用下一个swap()时,代码不会引发任何错误。交换与整数不兼容还是存在一些陷阱?
提前谢谢您的帮助! 编辑:我要交换的代码甚至没有任何意义。抱歉!
解决方法
您应该只使用std::swap
而不是您自己的
但是,对于您的错误的解释:
using namesapce std;
假设您的代码中实际上说了namespace
,那就是问题所在。有一个here。
如果您删除了using
指令并用std::
限定了std的使用,则可以将交换条件称为不合格的swap
in namespace std
#include <iostream>
#include <string>
template <typename T>
void swap(T &a,T &b) {
T temp = a; //Temporary copy to reuse
// a = (b = temp); // incorrect
a = b;
b = temp;
}
int main() {
int x,y;
std::cin >> x >> y;
std::cout << "X: " << x << "\t Y: " << y << '\n';
swap(x,y);
}
关于它为什么能与std::string
一起使用的原因:std::swap
的字符串重载比模板交换更匹配,因此编译器明确选择了该字符串
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。