Ambiguous C++ compiler error

4.2k Views Asked by At

The following bit of code fails to compile. The error seems to be some kind of ambigous call to the merge routine. My understanding is that STL has a merge routine found in the std namespace, but as far as I can tell the name merge in the code below should be unique.

If I rename merge to xmerge, everything works. What could the problem be? where is the name clash coming from?

http://codepad.org/uAKciGy5

#include <iostream>
#include <iterator>
#include <vector>

template<typename InputIterator1,
         typename InputIterator2,
         typename OutputIterator>
void merge(const InputIterator1 begin1, const InputIterator1 end1,
           const InputIterator2 begin2, const InputIterator2 end2,
           OutputIterator out)
{
   InputIterator1 itr1 = begin1;
   InputIterator2 itr2 = begin2;
   while ((itr1 != end1) && (itr2 != end2))
   {
      if (*itr1 < *itr2)
         *out = *itr1, ++itr1;
      else
         *out = *itr2, ++itr2;
      ++out;
   }
   while (itr1 != end1) *out++ = *itr1++;
   while (itr2 != end2) *out++ = *itr2++;
}

int main()
{
   std::vector<int> l1;
   std::vector<int> l2;
   std::vector<int> merged_list;

   merge(l1.begin(),l1.end(),
         l2.begin(),l2.end(),
         std::back_inserter(merged_list));

   return 0;
}
1

There are 1 best solutions below

6
On

Compiler is getting confused between your merge function and the std::merge defined in the algorithm. Use ::merge to remove this ambiguity. This call is ambiguous as compiler is using Argument Dependendent Lookup to search for the function when unqualified function name is used.