Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c++ - ambiguous call in template error

Can anyone tell me the cause of error ?

Error is

C:webemplate1.cpp||In function 'int main()':|
C:webemplate1.cpp|23|error: call of overloaded 'swap(int&, int&)' is ambiguous|
C:webemplate1.cpp|6|note: candidates are: void swap(X&, X&) [with X = int]|
c:program filescodeblocksmingwin..libgccmingw324.4.1includec++itsmove.h|76|note:                 void std::swap(_Tp&, _Tp&) [with _Tp = int]|
C:webemplate1.cpp|24|error: call of overloaded 'swap(double&, double&)' is ambiguous|
C:webemplate1.cpp|6|note: candidates are: void swap(X&, X&) [with X = double]|
c:program filescodeblocksmingwin..libgccmingw324.4.1includec++itsmove.h|76|note:                 void std::swap(_Tp&, _Tp&) [with _Tp = double]|
C:webemplate1.cpp|25|error: call of overloaded 'swap(char&, char&)' is ambiguous|
C:webemplate1.cpp|6|note: candidates are: void swap(X&, X&) [with X = char]|
c:program filescodeblocksmingwin..libgccmingw324.4.1includec++itsmove.h|76|note:                 void std::swap(_Tp&, _Tp&) [with _Tp = char]|
||=== Build finished: 3 errors, 0 warnings ===|

#include <iostream>

using namespace std;

template <typename X>
void swap(X &a, X &b)
{
    X temp = a;
    a = b;
    b = temp;
}

int main()
{
    int i=10, j=20;
    double x=10.1, y=23.3;
    char a='x', b='z';

    cout<<"i="<<i<<"j="<<j<<endl;
    cout<<"x="<<x<<"y="<<y<<endl;
    cout<<"a="<<a<<"b="<<b<<endl;

    swap(i,j);
    swap(x,y);
    swap(a,b);

    cout<<"i="<<i<<"j="<<j<<endl;
    cout<<"x="<<x<<"y="<<y<<endl;
    cout<<"a="<<a<<"b="<<b<<endl;

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your swap conflicts with std::swap. Remove using namespace std; above and correct the rest code from std namespace.

std::cout<<"i="<<i<<"j="<<j<<std::endl;
std::cout<<"x="<<x<<"y="<<y<<std::endl;
std::cout<<"a="<<a<<"b="<<b<<std::endl;

Also it's worth reading Why is "using namespace std" considered bad practice?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...