Kira Yamato wrote:
On 2007-11-19 07:12:29 -0500, yurec <Yurij.Zha...@materialise.kiev.ua>
said:
Hi
I wanna give template method of library class with some predicate,
which I put to std::for_each in that method.How to break the
std::for_each with predicate?(exceptions are used olny in exceptional
situations, as i know)
Thanks
I would think throwing an exception is a simple and elegant solution here.
Simple and elegant? in this case?
Compare
try {
std::for_each( seq.begin(), seq.end(), throwing_predicate_and_action );
}
catch ( whatever ) {}
to
for ( iterator_type iter = seq.begin();
iter != seq.end() && ! break_condition( *iter );
++iter ) {
some_action( *iter );
}
I cannot say that I find the try-throw-catch version easier to grok or more
elegant.
Just because we have called a mechanism 'exception' and gave it the
connotation that it is for error-handling purposes, does not mean that
we can only use the mechanism as such and nothing else.
I wholeheartly agree to that. I prefer to refer to the mechanism as
try-throw-catch or stack-unwinding to avoid connotations. Sometimes, when
someone says "exception are only to be thrown is exceptional
circumstances", I reply (only half-jokingly): "ok. so throw something
else".
Ok, so some runtime cost is needed to setup try-catch blocks, but I'm
not sure scanning the list twice with find_if/for_each combo is
necessarily faster.
No, but a simple for loop might be (and it also might convey intend better
than any of the alternatives).