Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 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 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...