Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an operator to a lambda

Tags:

c++

c++11

lambda

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;};

like image 865
tswanson-cs Avatar asked Jul 13 '26 06:07

tswanson-cs


2 Answers

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;
}
like image 178
DimChtz Avatar answered Jul 14 '26 19:07

DimChtz


I would do this:

C++14

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; });

C++11

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; });

Well, you could also do this:

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

C++14

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; }

C++11

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;
like image 44
bolov Avatar answered Jul 14 '26 19:07

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!