Is it possible to pass an operator to a lambda? For example passing some operator op to the function below.
auto lambdaCompare = [](value,compare1,compare2,op){return value op compare1 and value op compare2;};
You can't pass an operator and then use it like you want but you can pass std::greater_equal:
#include <iostream>
#include <functional>
int main() {
auto lambdaCompare = [](int value, int compare1, int compare2, std::function<bool(int, int)> op) {
return op(value, compare1) && op(value, compare2);
};
std::cout << lambdaCompare(2, 1, 6, std::greater_equal<int>());
return 0;
}
auto l = [](auto value, auto c1, auto c2, auto op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, [](int a, int b) { return a < b; });
auto l = [](int value, int c1, int c2, bool(* op)(int, int))
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, [](int a, int b) { return a < b; });
I am conflicted whether or not to actually recommend this. On one hand it's a macro yuck, on the other hand it looks pretty innocent, it's simple and self-explanatory
auto l = [](auto value, auto c1, auto c2, auto op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, OPERATOR(<));
l(1, 2, 3, OPERATOR(<=));
l(1, 2, 3, OPERATOR(>));
l(1, 2, 3, OPERATOR(>=));
l(1, 2, 3, OPERATOR(==));
l(1, 2, 3, OPERATOR(!=));
with
#define OPERATOR(op) [] (const auto& a, const auto& b) { return a op b; }
auto l = [](int value, int c1, int c2, Op_t<int, int, bool> op)
{
return (op(value, c1) && op(value, c2));
};
l(1, 2, 3, OPERATOR(int, int, <));
l(1, 2, 3, OPERATOR(int, int, <=));
l(1, 2, 3, OPERATOR(int, int, >));
l(1, 2, 3, OPERATOR(int, int, >=));
l(1, 2, 3, OPERATOR(int, int, ==));
l(1, 2, 3, OPERATOR(int, int, !=));
with
#define OPERATOR(T1, T2, op) [] (const T1& a, const T2& b) { return a op b; }
template <class T1, class T2, class R>
using Op_t = auto (*) (const T1&, const T2&) -> R;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With