Can we pass a basic operator "<" as a callable argument?

57 Views Asked by At

My low-level routine needs a argument, to specify it should compare data with LessThan(<) or GreatThan(>) operator.

Like this:

using CompOp_f = std::function<bool( double, double )>;
struct LowLevelObj_t {
    bool doChecking() {
        return _op( _x, _y );
    };

    CompOp_f _op;
    double   _x;
    double   _y;
};

When using it, I have to do as following:

LowLevelObj_t a {
    ._op = []( double l_, double r_ ) { return l_ < r_; },
    ._x = -1.,
    ._y = 1.,
};

// when I need it with LessThan
bool pos_result = a.doChecking();

// when I need it with GreatThan
a._op = []( double l_, double r_ ) { return l_ > r_; };
bool neg_result = a.doChecking();

I want to do it like this:

// when I need it with LessThan
a._op = <;
bool pos_result = a.doChecking();

// when I need it with GreatThan
a._op = >;
bool neg_result = a.doChecking();

In this way, I can make it not only more readable, but also faster? Because with using a lambda obj, there are some extra overhead?

Can I do it in any way?

How to get it?

I know I can do it with template syntax, and then specialize LowLevelObj_t with different arguments. But in that way, I have to code doChecking() twice, because the real logic is very complex.

0

There are 0 best solutions below