简体   繁体   中英

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

I am trying to implement a custom binary search to run over a vector of dates.

My binary search function is the following:

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 I am using is defined as:

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

These two compile without issues, 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?

You're passing the name of a template ( cmp ) in a context where C++ wants a value. Apart from the fact that you can't do this, it's a chicken-or-egg problem: what type is cmp ? A function's type depends on its arguments, and this function can take arguments of any type. So what type does the compiler infer for the template argument Comparer ? It would have to look at the body of the function to figure out that you expect int , and that's not always possible—the compiler doesn't always have access to the source code of templates.

You need to specifically select the type for the function template that you're passing. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM