2012-03-30 10 views
0

誰も私にエラーの原因を教えてもらえますか?テンプレートエラーのあいまいな呼び出し

エラーが

C:\web\template1.cpp||In function 'int main()':| 
C:\web\template1.cpp|23|error: call of overloaded 'swap(int&, int&)' is ambiguous| 
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = int]| 
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.h|76|note:     void std::swap(_Tp&, _Tp&) [with _Tp = int]| 
C:\web\template1.cpp|24|error: call of overloaded 'swap(double&, double&)' is ambiguous| 
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = double]| 
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.h|76|note:     void std::swap(_Tp&, _Tp&) [with _Tp = double]| 
C:\web\template1.cpp|25|error: call of overloaded 'swap(char&, char&)' is ambiguous| 
C:\web\template1.cpp|6|note: candidates are: void swap(X&, X&) [with X = char]| 
c:\program files\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.4.1\include\c++\bits\move.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<<"\tj="<<j<<endl; 
    cout<<"x="<<x<<"\ty="<<y<<endl; 
    cout<<"a="<<a<<"\tb="<<b<<endl; 

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

    cout<<"i="<<i<<"\tj="<<j<<endl; 
    cout<<"x="<<x<<"\ty="<<y<<endl; 
    cout<<"a="<<a<<"\tb="<<b<<endl; 

    return 0; 
} 

答えて

10

swapstd::swapと競合しています。上記のusing namespace std;を削除し、残りのコードをstd名前空間から修正します。

std::cout<<"i="<<i<<"\tj="<<j<<std::endl; 
std::cout<<"x="<<x<<"\ty="<<y<<std::endl; 
std::cout<<"a="<<a<<"\tb="<<b<<std::endl; 

また、それはswap2()などの名前の変更swap()Why is "using namespace std" considered bad practice?

0

はすでにあなたのコードのどこかで宣言スワップ機能があります。関数の名前を変更するか、他のスワップ関数の宣言を削除します。

2

を読む価値があります。または、良い、決してusing namespace std;を発行しないでください。書かれたよう

、あなたのコードはstd::swap()経由のiostream、を紹介し、その後using namespaceすることにより、独自のswap()の上にそれをダンプします。

関連する問題