The most strange thing i have ever met : just change a name, everything fails!

I wrote a template function to resemble the find generic algorithm, of course ,it's a very simple function , it is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
#include<vector>
using namespace std;
template < class T, typename Y >
typename T::iterator find( typename T::iterator beg  , typename T::iterator end , Y val )
{
while( *beg != val && beg ++ != end );
return beg;
}

int main()
{
vector<int> ivec;
int num;
cout << "Please enter some integers : " << endl;
while( cin >> num ) ivec.push_back( num);
cin.clear();
cout << "Please enter an integer you want to look for : " << endl;
cin >> num;
vector<int>::iterator it = ivec.begin();
if( ( it = find( it , ivec.end() , num ) ) != ivec.end() )
cout << "Find : " << *it << endl;
else cout << "Cannot finf it !" << endl;
return 0;
}

It compiles and works fine!
But, if i replace the function name "find" with some other names , it cannot get through the compiling... The compiler will say : "no matching function for call to ... " , OMG, i am really surprised, what's wrong?
I tried plenty of times, the symptom remains. I need your help.
For me your code gives an error "could not deduce template argument for 'T'".
I changed it to
T find(T beg, T end, Y val)
and it worked fine.
I think your problem with renaming 'find' is that your code in fact used another 'find' function http://www.cplusplus.com/reference/algorithm/find/ .
As hamsterman said, probably,your code invokes stl find .
Definition of STL find
1
2
3
4
5
6
template<class InputIterator, class T>
  InputIterator find ( InputIterator first, InputIterator last, const T& value )
  {
    for ( ;first!=last; first++) if ( *first==value ) break;
    return first;
  }

you shall use T instead of , T::iterator .
Such as
1
2
3
4
5
6
template < class T, typename Y >
T find(  T beg  , T end , Y val )    
{
while( *beg != val && beg ++ != end );
return beg;
}

As mentioned I think the compiler is using std::find because you have a "using namespace std" at the top of your code. So I suspect your template function never gets instantiated until you change its name. Then its errors show up when the compiler tries to deal with it.
Last edited on
Yeah, I changed the function so as to match what hamsterman suggested, it worked! Thanks for your help, hamsterman, Dufresne, and Galik.
Topic archived. No new replies allowed.