Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c++ - 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?

question from:https://stackoverflow.com/questions/21831094/why-is-this-cast-to-bool-required

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...