Skip to content

Instantly share code, notes, and snippets.

@castano
Last active January 2, 2023 11:13
Show Gist options
  • Save castano/84ff3456fbdb6ce502c633a5d0b38d33 to your computer and use it in GitHub Desktop.
Save castano/84ff3456fbdb6ce502c633a5d0b38d33 to your computer and use it in GitHub Desktop.
Using qsort with lambdas
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