helix - 1 year ago 95

C++ Question

I have a

`class A`

`sort()`

`#include <iostream>`

#include <vector>

class A{

float val;

int i;

public:

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

`sort()`

`main()`

`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?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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 {
...
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**