Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this cast to bool required?

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?

like image 423
qdii Avatar asked Feb 17 '14 14:02

qdii


People also ask

Can a BOOLEAN be type casted?

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.

How do I assign an int to a Boolean?

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.


2 Answers

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.

like image 85
Simple Avatar answered Sep 20 '22 23:09

Simple


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).

like image 26
James Kanze Avatar answered Sep 19 '22 23:09

James Kanze