Last active
September 7, 2015 22:35
-
-
Save daniel-j-h/2685cbcc48a4a918d31e to your computer and use it in GitHub Desktop.
compare greater on age
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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assignment for you dear reader: extend with variadic template to be able to say:
which would semantically be the same as: