jeudi 24 août 2017

In C++ is it possible to write a lambda that returns a value but without using the return statement

Example (contrived):

I've written a method that takes can take a "filter" expression, and returns the number of matching items:

int getCount(std::function<bool(int, int)> filter)
{
    // Iterate pairs of numbers p,q
    // Count number of pairs where filter(p, q) is true
    // Return count
}

I know I can invoke this as follows:

getCount([](int x, int y) { return x > y; });

But, since the intention is to write a filter "condition" or "expression" i.e. something very declarative and not imperative, I would ideally like to exclude the "return" statement.

E.g.:

getCount([](int x, int y) { x > y; });

Or possibly even the semicolon, but that may be just being cheeky:

getCount([](int x, int y) { x > y });

Is either of the above possible in C++? (Obviously it's not possible, as it won't compile, but I mean is there an alternative e.g. in std or boost that provides an alternative notation?)

Aucun commentaire:

Enregistrer un commentaire