Last active
January 2, 2023 11:13
-
-
Save castano/84ff3456fbdb6ce502c633a5d0b38d33 to your computer and use it in GitHub Desktop.
Using qsort with lambdas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
struct Compare { | |
T lambda; | |
#if _MSC_VER || __APPLE__ | |
static int compare(void * cmp, const void * a, const void * b) | |
#else | |
static int compare(const void * a, const void * b, void * cmp) | |
#endif | |
{ | |
return ((Compare<T>*)cmp)->lambda(a, b); | |
} | |
}; | |
template <typename F> | |
void qsort(void *base, size_t num, size_t width, F cmp) { | |
Compare<F> f { cmp }; | |
#if _MSC_VER | |
qsort_s(base, num, width, Compare<F>::compare, &f); | |
#elif __APPLE__ | |
qsort_r(base, num, width, &f, Compare<F>::compare); | |
#else | |
qsort_r(base, num, width, Compare<F>::compare, &f); | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment