为什么这个演员需要布尔?
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; }
我碰到了GCC 4.7.0附带的C ++标准库实现源代码片段 。 这是一个input迭代器的find_if的特化。 我清除了主要的下划线,使其更具可读性。
为什么他们在谓词上使用boolexpression式?
原因是,只要写!pred(*first)可能导致调用一个重载的operator! 而不是调用explicit operator bool 。
有趣的是,这个措施是用pred ,但是在所提供的实现中仍然可以select一个重载operator&& 。 first != last将需要更改为bool(first != last)以防止这种过载。
该标准只要求谓词在可以转换为bool的上下文中是可用的。 据推测,一个“谓词”对象可以有一个operator bool函数,这是正确的,一个operator! 做了一些完全不相关的function。 (当然,这将是一个可怕的devise,但是标准要求库按照规定工作,不pipe用户代码是多么糟糕。)所以g ++转换为bool ,然后使用! 根据转换的结果(只有内置运算符可以应用)。
在C ++标准中,有关于谓词的写法
换句话说,如果一个algorithm将Predicate pred作为它的参数,并且首先作为它的迭代器参数,它应该在构造pred(* first)的上下文中转换为bool
“上下文转换为bool”这个词意味着,即使一个类定义了一个转换函数,将该类的一个对象作为一个显式操作符转换为bool,它也应该被应用。 考虑一个上下文转换为bool的例子
#include <iostream> struct A { explicit operator bool () const { return true; } }; int main() { if ( A() ) { std::cout << "Here is a contextual conversion to bool" << std::endl; } }
所以在C ++标准的语境中,我没有看到写expression式的任何意义
first != last && !bool( pred(*first ) )
写就足够了
first != last && !pred(*first )
这里pred是上下文转换为bool。