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

孤街浪徒 提交于 2019-12-23 04:11:48

问题


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?


回答1:


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>);


来源:https://stackoverflow.com/questions/11380521/c-unresolved-overloaded-function-type-with-comparison-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!