Question

In the following code, I have to qualify the equal() call (otherwise I get "ambiguous call to overloaded function"), but can call unqualified find(). What's the difference?

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

using std::vector;
using std::cout;
using std::endl;

// Test whether the elements in two ranges are equal.
// Compares the elements in the range [b,e) with those in the range
// beginning at d, and returns true if all of the elements in both ranges match.
template <class InIter1, class InIter2>
bool equal(InIter1 b, InIter1 e, InIter2 d)
{
    cout << "My equal()" << endl;
    while (b != e)
        if ((*b++) != (*d++))
            return false;
    return true;
}

// Returns an iterator to the first element in the range [b,e)
// that compares equal to t. If no such element is found, the function returns last.
template <class InIter, class T>
InIter find( InIter b, InIter e, const T& t )
{
    cout << "My find()" << endl;
    while (b != e) {
        if ( *b == t )
            return b;
        b++;
    }

    return e;
}

/* "Accelerated C++", ex. 8.2 */
int main()
{
    static const int arr[] = {8, 7, 15, 21, 30};
    vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]) );

    cout << "equal() result: " << ::equal(vec.begin(), vec.end(), vec.rbegin()) << endl;

    vector<int>::iterator iter = find(vec.begin(), vec.end(), 21);
    if (iter == vec.end())
        cout << "did not find()" << endl;
    else
        cout << "find() result: " << *iter << endl;

    return 0;
}

I think it is related to argument dependent lookup (see this question), but still do not see why those two calls are different.

Était-ce utile?

La solution

It appears that your standard library implementation brings std::equal in from some other file which does not also bring in std::find (perhaps it's used for vector's comparison operator). If you include <algorithm>, they will both be brought in, and you will get an ambiguity for both cases.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top