Skip to content

Instantly share code, notes, and snippets.

@daniel-j-h
Last active September 7, 2015 22:35
Show Gist options
  • Save daniel-j-h/2685cbcc48a4a918d31e to your computer and use it in GitHub Desktop.
Save daniel-j-h/2685cbcc48a4a918d31e to your computer and use it in GitHub Desktop.
compare greater on age
#include <iostream>
#include <ostream>
#include <algorithm>
#include <iterator>
#include <functional>
#include <type_traits>
struct Person {
int age;
friend std::ostream& operator<<(std::ostream& out, const Person& person) {
return out << person.age;
}
};
// https://hackage.haskell.org/package/base-4.8.1.0/docs/Data-Function.html#v:on
template <typename Cmp, typename MemPtr>
auto inline on(Cmp cmp, const MemPtr memPtr) {
static_assert(std::is_member_pointer<MemPtr>(), "requires member pointer");
return [=](const auto& lhs, const auto& rhs) {
return cmp(lhs.*memPtr, rhs.*memPtr);
};
}
int main() {
std::vector<Person> persons{{0}, {1}, {2}};
std::sort(begin(persons), end(persons), on(std::greater<>{}, &Person::age));
for (auto&& each : persons)
std::cout << each << std::endl;
}
@daniel-j-h
Copy link
Author

Assignment for you dear reader: extend with variadic template to be able to say:

on(std::greater<>{}, &Person::age, &Person::firstName, &Person::lastName);

which would semantically be the same as:

operator<(const Person& lhs, const Person& rhs) {
  return std::tie(lhs.age, lhs.firstName, lhs.lastName) > std::tie(rhs.age, rhs.firstName, rhs.lastName);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment