Better name needed for applying a function on elements of a container
I have a co开发者_JAVA技巧ntainer class (containing a multi-index container) for which I have a public "foreach" member-function, so users can pass a functor to apply on all elements.
While implementing, I had a case where the functor should only be applied to some elements of a range in the container, so I overloaded the foreach, to pass some valid range. Now, in some cases, it was worthwhile to stop on a certain condition, so practically, I let the foreach stop based on the return-value of the function.I'm pleased with how the system works, but I have one concern:
How should a "foreach" on a range, with stop conditions be called? Anyone knows a generic, clear and concise name?Based on your description, i'd go for apply_until()
.
Maybe until
or something?
How about find_if(...)
, as in stl ?
I'd probably call it either foreach_until
or foreach_while
(attempting to follow a convention based on the _if
functions like replace_if
and remove_if
, except that the condition here isn't "if" each one is true, it's "until" the end condition holds). Or just foreach
. std::for_each
ignores the return value of the functor, but that doesn't necessarily mean that your function called foreach
has to. I think it's a pretty common idiom for a callback function to have a return value allowing early exit from the controlling loop.
If the callback returns either a false value (to continue) or a true value (to halt), then you could call the function find_if
. That's basically what it is, and it could be implemented using std::find_if
, even if the caller isn't interested in which iterator provoked the end condition.
If you can provide a subset function that returns a view of the elements of interest, maybe you don't need apply_until(). Just myContainer.subset(3, 17).foreach(myFunctor)
I think that's a better separation of concerns.
a generic name? ConditionalIterator? RangeIterator? Or since it's a function, perhaps IterateRange?
精彩评论