There is a class that contains some data and it sorts them at some point of time. I use qsort()
and I'd like to keep the comparing function within the class as a method. The question is how to pass a method to qsort()
so that the compiler (g++) don't throw any warnings?
Attempt 1:
int Data::compare_records(void * rec_1, void * rec_2){
// [...]
}
void Data::sort(){
qsort(records, count, sizeof(*records), &Data::compare_records);
}
This way generates an error:
error: cannot convert ‘int (Data::*)(const void*, const void*)’ to ‘int (*)(const void*, const void*)’ for argument ‘4’ to ‘void qsort(void*, size_t, size_t, int (*)(const void*, const void*))’
Attempt 2 :
void Data::sort(){
qsort(
records, count, sizeof(*records),
(int (*)(const void*, const void*)) &Data::compare_records
);
}
This way generates a warning:
warning: converting from ‘int (Data::*)(const void*, const void*)’ to ‘int (*)(const void*, const void*)’
How to do it the right way then?
If you must use qsort
and not std::sort
(recommended), declaring the member method as static
should be enough.
You pass the function as &Data::compare_records
, but you should pass it as Data::compare_records
and also make it static
Don't use qsort
in C++. Use std::sort
and boost/std::bind
. Member function-pointer cannot been converted to function-pointer. Your method should be static
, or it should be free function
.
see Is the type of “pointer-to-member-function” different from “pointer-to-function”? for an explanation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With