4 ms·
The syntax might seem strange to you, but this is pretty slick: bool batch_failed = std::any_of( jobs.begin(), jobs.end(), [](const auto &
by humanrebar 9y ago
The syntax might seem strange to you, but this is pretty slick:
bool batch_failed = std::any_of(
jobs.begin(), jobs.end(),
[](const auto & job) { return job.failed(); }
);
In C++03-plus-auto, you'd have to define an helper function or class:
bool isJobFailed(const Job& job) {
return job.failed();
}
And then use find_if, I guess:
auto last = jobs.end();
auto iter = std::find_if(
jobs.begin(), jobs.end(),
isJobFailed
);
bool batch_failed = (iter == last);
- Koshkin 9y agoDoesn't look pretty, does it? Now compare this with what it could have been: jobs.Any(job => job.failed()) (Lambdas in C++ is one ridiculous example where I must use all the existing types of brackets in one expression: [](){} is a lambda.)
- nly 9y agoWhat is 'jobs' in your pseudo-code? Can it be a user-defined type? Does the author of that class need to explicitly state that their type meets some trait? Is 'Any' part of the type, a trait, or the language? What humanrebar wrote is an algorithm that will work with any range of any type that has a 'failed()' member function. Here's another formalisation: auto batch_failed = [](auto const& batch) { return std::any_of (begin (batch), end (batch), [](auto& testcase) { return testcase.failed (); }); } This function will basically work with anything.
- pcwalton 9y agoThis comment is nonresponsive to the parent comment. The complaint (which I happen to agree with) is that both iterators/ranges and lambda syntax are too verbose in C++.
- Davidbrcz 9y agoYou can't argue that the current C++ syntax is verbose and cumbersome. 99% of the time, I work on the full container, why not providing an overload which let me write at least bool batch_failed = std::any_of(jobs, [](const auto & job) { return job.failed();} ); Then, lambas are verbose. I would like to have a simpler syntax like for simple lambas (no capture, single expression in the lamba body). job could be automatically typed with const auto&, or you could write it yourself if you wish. job => return job.failed(); And a the current one, which is more verbose, for more complex lambas (capture, several expressions in the body)