c++ - 为什么需要强制转换为 bool 值?

标签 c++ gcc casting standard-library

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;
}

我碰到了this snippet在 GCC 4.7.0 附带的 C++ 标准库的实现的源代码中。这是输入迭代器的 find_if 的特化。我清理了前导下划线以使其更具可读性。

为什么他们在谓词上使用 bool 类型转换?

最佳答案

原因是仅仅编写 !pred(*first) 可能会导致调用重载的 operator! 而不是调用 explicit operator bool .

有趣的是,这个措施是针对 pred 采取的,但是在提供的实现中仍然可以选择重载的 operator&&first != last 需要更改为 bool(first != last) 以防止这种过载。

关于c++ - 为什么需要强制转换为 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21831094/

相关文章:

c++ - 是否有隐式模板<typename T>运算符<<(const ostream&,T)?

c++ - 为什么这个 SFINAE 在 gcc 中会报错?

c - 系统函数调用时出现段错误

c++ - 即使锁定失败,带有 try_to_lock 的 unique_lock 是否应该拥有互斥锁?

c# - 将字符串转换为日期时间

c++ - 如何在 C++ 中声明 std::chrono::duration<double> 变量

c++ - 游戏中的射击按钮在按下空格键时触发多次而不是一次

C++ : Why this window title gets truncated?

c - 在 C 中使用 malloc 时是否需要类型转换?

c - 解释C中的一行代码——指针和强制转换