helix helix - 10 months ago 63
C++ Question

c++ - <unresolved overloaded function type> in function template calling

I have a

class A
with two attributes val(float) and i(int). I created
function implementing quicksort which accepts two function pointers - first which accepts two class A type objects which allows me to choose which attribute to sort on and second which is a template function which allows me to choose whether to sort in increasing or decreasing order. The implementation is as follows:

#include <iostream>
#include <vector>

class A{
float val;
int i;
A(float v, int j): val(v), i(j){} //constructor
float getVal(){ return val;}
float getI(){ return i;}

template <typename T>
bool compareVal(A _One, A _Two, bool (*comparator)(T,T)){
return comparator(_One.getVal(),_Two.getVal());}

template <typename T>
bool compareI(A _One, A _Two, bool (*comparator)(T,T)){
return comparator(_One.getI(),_Two.getI());}

template <typename T>
bool less(T a, T b){
return a<b;

template <typename T>
bool greater(T a, T b){
return a>b;

//a quicksort program
template <typename T>
void sort(std::vector<A>& _as, int left, int right, bool (*compare)(A, A),
bool (*comparator)(T,T)){
int i = left, j = right;
int middle = (left + right)/2;;
if (right - left < 1) return;
while (i <= j) {
while (compare(_as[i],_as[middle], comparator)) i++; //compare called
while (compare(_as[middle],_as[j], comparator)) j--; //compare called
if (i <= j) { std::swap(_as[i], _as[j]); i++; j--; }
if (left < j) sort(_as, left, j, compare, comparator);
if (i < right) sort(_as, i, right, compare, comparator);

int main(){
std::vector<A> v;
//some inserts
sort(v, 0, v.size()-1, compareVal, less<float>); // first call
sort<float>(v, 0, v.size()-1, compareVal, less); // second call
sort<float>(v, 0, v.size()-1, compareVal, less<float>); //third call
return 0;

But, when
function is called from
it gives a compiler error in all the three instances as:

error: no matching function for call to ‘sort(std::vector<A>&, int, std::vector<A>::size_type,
<unresolved overloaded function type>, <unresolved overloaded function type>)’

I am unable to understand the error. Looked at some previous stackoverflow questions related to this but still nothing. How to make this program work?

Answer Source

compare is declared to be a bool(*)(A, A), but compareVal and compareI both have the type bool(*)(A, A, bool(*)(T, T)). Change the signature of sort accordingly:

template <typename T>
void sort(std::vector<A>& _as, int left, int right,
              bool (*compare)(A, A, bool(*)(T, T)),
              bool (*comparator)(T, T)){

Alternatively, ditch the function pointers altogether and use templates to allow any callable to be used (e.g. lambdas):

template <typename T, typename CompareT, typename ComparatorT>
void sort(std::vector<A>& _as, int left, int right,
              CompareT compare, ComparatorT comparator {