Why is this cast to bool required?

c++, casting, gcc, standard-library

Solution

The reason is that just writing `!pred(*first)` could result in a call to an overloaded `operator!` rather than the call to `explicit operator bool`.

It's interesting that this measure was taken for `pred`, but an overloaded `operator&&` can still be selected in the implementation provided. `first != last` would need to be changed to `bool(first != last)` to also prevent this overload.

Problem

``` template<typename InputIterator, typename Predicate> inline InputIterator find_if(InputIterator first, InputIterator last, Predicate pred, input_iterator_tag) { while (first != last && !bool(pred(*first))) ++first; return first; } ``` I bumped into this snippet in the source code of the implementation of the C++ standard library shipped with GCC 4.7.0. This is the specialization of `find_if` for an input iterator. I cleaned the leading underscores to make it more readable. Why did they use a `bool` cast on the predicate?

Original source