How to pass a method to qsort?

c++

Solution

You pass the function as `&Data::compare_records`, but you should pass it as `Data::compare_records` and also make it `static`

Problem

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?

Original source