模糊调用模板错误 [英] ambiguous call in template error

查看:140
本文介绍了模糊调用模板错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我错误的原因吗?

Can anyone tell me the cause of error ?

错误是

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;
}


推荐答案

您的 swap std :: swap 冲突。使用上述命名空间std; 删除,并从 std 命名空间中更正其余代码。

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

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

此外,值得阅读为什么是'using namespace std;'在C ++中被认为是不好的做法吗?

这篇关于模糊调用模板错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆