C ++ <unresolved overloaded function type> with comparison function

I am trying to implement a custom binary search to start a date vector.

My binary search function is as follows:

 template <typename RandomAccessIterator, typename Value, typename Comparer> inline int binary_search(RandomAccessIterator const first, RandomAccessIterator const last, Value const& value, Comparer comparer) { RandomAccessIterator it(std::lower_bound(first, last, value, comparer)); if (it == last || comparer(*it, value) || comparer(value, *it)) return distance(first,last); return distance(first,it); } 

The comparator that I use is defined as:

 template <class T> inline bool cmp(T lhs,T rhs) { return lhs<rhs; } 

These two compile without problems, however I get a compilation error when I try to call the binary_search function using the following code:

 binary_search(date_list.begin(),date_list.end(),date2,cmp) 

where date_list is a vector containing dates, date2 is an int.

The exact error message is:

 error: no matching function for call to ?binary_search(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, int&, <unresolved overloaded function type>)? 

Any ideas on how to solve this?

+1
source share
1 answer

You pass the template name ( cmp ) in the context where C ++ wants the value. Besides the fact that you cannot do this, this is a problem with a chicken or an egg: what type of cmp ? The type of function depends on its arguments, and this function can accept arguments of any type. So, what type does the compiler output for the Comparer template argument? He would have to look at the body of the function to understand that you are expecting an int , and this is not always possible - the compiler does not always have access to the source code of the templates.

You need to specifically select the type of function template that you are passing. For instance:

 binary_search(date_list.begin(), date_list.end(), date2, cmp<int>); 
+5
source

Source: https://habr.com/ru/post/919951/


All Articles