Last active
October 9, 2021 03:50
-
-
Save rileylev/f5b44c236ce3b1124f29fea9eb2f93d5 to your computer and use it in GitHub Desktop.
A silly macro for a shorthand for lambdas
This file contains hidden or 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
namespace FN_impl { | |
template<class T> | |
constexpr auto delay(auto x) { | |
return x; | |
} | |
struct no_arg_passed { | |
template<class T> | |
operator T() { | |
static_assert(delay<T>(false), | |
"Insufficient arguments were passed to a FN lambda"); | |
return {}; | |
} | |
}; | |
} // namespace FN_impl | |
#define FN(...) \ | |
<class T0 = ::FN_impl::no_arg_passed, \ | |
class T1 = ::FN_impl::no_arg_passed, \ | |
class T2 = ::FN_impl::no_arg_passed, \ | |
class T3 = ::FN_impl::no_arg_passed, \ | |
class T4 = ::FN_impl::no_arg_passed, \ | |
class T5 = ::FN_impl::no_arg_passed> \ | |
([[maybe_unused]] T0 _0 = {}, \ | |
[[maybe_unused]] T1 _1 = {}, \ | |
[[maybe_unused]] T2 _2 = {}, \ | |
[[maybe_unused]] T3 _3 = {}, \ | |
[[maybe_unused]] T4 _4 = {}, \ | |
[[maybe_unused]] T5 _5 = {}) { \ | |
auto& _ = _0; \ | |
return __VA_ARGS__; \ | |
} | |
// usage: | |
struct point { | |
int x; | |
int y; | |
} | |
auto less_x = []FN(_0.x < _1.x); | |
auto less_y = []FN(_0.y < _1.y); | |
template<class Less = std::less> | |
constexpr auto compare_by(auto projection, Less less = {}){ | |
return [=]FN(less(projection(_0), projection(_1))); | |
} | |
// now you can write these more easily: | |
auto less_x_better = compare_by([]FN(_.x)); | |
auto less_y_better = compare_by([]FN(_.y)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment