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?
You can cast DECIMAL values to BOOLEAN , with the same treatment of zero and non-zero values as the other numeric types. You cannot cast a BOOLEAN to a DECIMAL . You cannot cast a STRING value to BOOLEAN , although you can cast a BOOLEAN value to STRING , returning '1' for true values and '0' for false values.
The Convert. ToBoolean() method converts an integer value to a boolean value in C#. In C#, the integer value 0 is equivalent to false in boolean, and the integer value 1 is equivalent to true in boolean.
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.
The standard requires only that the predicate be usable in a context where it can convert to a bool
. Presumably, a "predicate" object could have an operator bool
function, which did the right thing, and an operator!
function which did something totally unrelated. (Of course, that would be horrible design, but the standard requires the library to work as specified, regardless of how bad the user code is.) So g++ converts to bool
, and then uses !
on the result of that conversion (where only the build-in operator can apply).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With