我在 C++ 中使用 void swap() 对这个函数进行模板化时有什么巧合吗?

Oun*_*ces 1 c++ templates function

我目前使用的是 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)",
Run Code Online (Sandbox Code Playgroud)

这是我写的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

有趣的是,当我调用下一个 swap() 时,代码不会抛出任何错误。交换与整数不兼容还是有一些问题?

提前感谢您的帮助!编辑:我要交换的代码甚至没有意义。对不起!

Rya*_*ing 5

你应该只是使用std::swap而不是你自己的。

但是,为了解释您的错误:

using namesapce std;
Run Code Online (Sandbox Code Playgroud)

假设实际上namespace在您的代码中说,这就是问题所在。有一个swapnamespace std

如果您删除using指令并限定您的 std 使用,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);
}
Run Code Online (Sandbox Code Playgroud)

至于为什么它碰巧适用于std::string:有一个重载的std::swapfor 字符串比模板化交换更好匹配,因此编译器明确地选择了那个

https://en.cppreference.com/w/cpp/string/basic_string/swap2