Namespaces
Variants

std::ranges::view_interface<D>::operator bool

从 zh.cppreference.net
 
 
范围库
范围适配器
 
 
constexpr explicit operator bool() requires /* see below */;
(1) (C++20 起)
constexpr explicit operator bool() const requires /* see below */;
(2) (C++20 起)

operator bool 成员函数的默认实现检查视图是否非空。它使得派生类型可以上下文转换到 bool。

1) 设 derived 为 static_cast<D&>(*this)。requires 子句中的表达式等于 requires { ranges::empty(derived); },函数体等价于 return !ranges::empty(derived);。
2) 同 (1),除了 derived 是 static_cast<const D&>(*this)。

返回值

当派生类型的值为空时(由 std::ranges::empty 判定)返回 false ,否则返回 true 。

注释

在 C++20 中,标准库中所有派生自 std::ranges::view_interface 的类型均未提供自定义的 operator bool 。这些类型几乎都使用默认实现。

一个显著的例外是 std::ranges::basic_istream_view 。由于其迭代器类型永远不满足 forward_iterator 要求,该视图无法使用继承的 operator bool 。

示例

#include <array>
#include <iostream>
#include <ranges>
int main()
{
    const std::array ints {0, 1, 2, 3, 4};
    auto odds = ints | std::views::filter([](int i) { return 0 != i % 2; });
    auto negs = ints | std::views::filter([](int i) { return i < 0; });
    std::cout << std::boolalpha
              << "Has odd numbers: " << (!!odds) << ' ' << '\n'
              << "Has negative numbers: " << (!!negs) << ' ' << '\n';
}

输出:

Has odd numbers: true
Has negative numbers: false

参见

检查范围是否为空
(定制点对象)
返回派生视图是否为空,仅在满足 sized_range 或 forward_range 时提供
(公开成员函数)
(C++17)
检查容器是否为空
(函数模板)