call of overloaded 'xxx' is ambiguous

这里定义了一个模版函数,功能同STL里的copy函数:

#include <vector>
#include <list>
#include <iostream>

template <typename Iter1, typename Iter2>
Iter2 copy(Iter1 f1, Iter1 e1, Iter2 f2)
{
    for (f1; f1 != e1; ++f1, ++f2)
    {
        *f1 = *f2;
    }
    return f2;
}

int main()
{
    int arr[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    copy(arr, arr + 10, vec.begin());
    return 0;
}

编译时报了call of overloaded 'copy(int [10], int*, std::vector<int>::iterator)' is ambiguous错误。

c:\Source\drill.cpp: In function 'int main()':
c:\Source\drill.cpp:27:36: error: call of overloaded 'copy(int [10], int*, std::vector<int>::iterator)' is ambiguous
     copy(arr, arr + 10, vec.begin());
                                    ^
c:\Source\drill.cpp:6:7: note: candidate: Iter2 copy(Iter1, Iter1, Iter2) [with Iter1 = int*; Iter2 = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
 Iter2 copy(Iter1 f1, Iter1 e1, Iter2 f2)
       ^~~~
In file included from C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/6.3.0/include/c++/vector:60:0,
                 from c:\Source\drill.cpp:1:
C:/mingw-w64/lib/gcc/x86_64-w64-mingw32/6.3.0/include/c++/bits/stl_algobase.h:446:5: note: candidate: _OI std::copy(_II, _II, _OI) [with _II = int*; _OI = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]
     copy(_II __first, _II __last, _OI __result)

从报错信息可以看出,编译器匹配到了stl_algobase.h里的copy函数,因为我传的参数std::vector::iterator(vec.begin())是属于namespace std的。

解决的办法一:指定命名空间

#include <vector>
#include <list>
#include <iostream>
namespace LK
{
    template <typename Iter1, typename Iter2>
    Iter2 copy(Iter1 f1, Iter1 e1, Iter2 f2)
    {
        for (f1; f1 != e1; ++f1, ++f2)
        {
            *f1 = *f2;
        }
        return f2;
    }
}

int main()
{
    int arr[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    LK::copy(arr, arr + 10, vec.begin());
    return 0;
}

解决的办法二:函数名用括号包住

#include <vector>
#include <list>
#include <iostream>

template <typename Iter1, typename Iter2>
Iter2 copy(Iter1 f1, Iter1 e1, Iter2 f2)
{
    for (f1; f1 != e1; ++f1, ++f2)
    {
        *f1 = *f2;
    }
    return f2;
}

int main()
{
    int arr[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    (copy)(arr, arr + 10, vec.begin());
    return 0;
}

参考资料

  1. template programming: ambiguous call to overloaded function
  2. Argument-dependent name lookup
  3. Argument-dependent lookup
posted @ 2017-10-04 15:56  ,,,沙子,,,  阅读(4442)  评论(0编辑  收藏  举报