命名空间
变体
操作

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

来自 cppreference.cn
 
 
范围库
范围适配器
 
 
constexpr explicit operator bool() requires /* 见下方 */;
(1) (自 C++20 起)
constexpr explicit operator bool() const requires /* 见下方 */;
(2) (自 C++20 起)

默认的 operator bool 成员函数实现检查视图是否为空。它使派生类型 语境可转换 (contextually convertible) 为 bool

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

目录

[编辑] 参数

(无)

[编辑] 返回值

false 如果派生类型的值为空(由 std::ranges::empty 确定),否则为 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_rangeforward_range 时才提供,返回派生视图是否为空
(公共成员函数) [编辑]
(C++17)
检查容器是否为空
(函数模板) [编辑]