std::unreachable_sentinel_t, std::unreachable_sentinel

来自cppreference.com
< cpp‎ | iterator
 
 
迭代器库
迭代器概念
迭代器原语
算法概念与工具
间接可调用概念
常用算法要求
(C++20)
(C++20)
(C++20)
工具
(C++20)
迭代器适配器
unreachable_sentinel_tunreachable_sentinel
(C++20)(C++20)
范围访问
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
在标头 <iterator> 定义
struct unreachable_sentinel_t;
(1) (C++20 起)
inline constexpr unreachable_sentinel_t unreachable_sentinel{};
(2) (C++20 起)
1) unreachable_sentinel_t 是能用于表示无界区间“上界”的空类类型。
2) unreachable_sentinelunreachable_sentinel_t 类型的常量。

非成员函数

operator==
(C++20)
比较一个 unreachable_sentinel_t 与任何 weakly_incrementable 类型的值
(函数模板)

operator==(std::unreachable_sentinel_t)

template<std::weakly_incrementable I>

friend constexpr bool operator==( unreachable_sentinel_t, const I& ) noexcept

{ return false; }
(C++20 起)

unreachable_sentinel_t 能与任何 weakly_incrementable 类型比较,而结果始终为 false

此函数模板对常规的无限定有限定查找不可见,而只能在 std::unreachable_sentinel_t 为实参的关联类时由实参依赖查找找到。

示例

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
 
template<class CharT>
constexpr std::size_t strlen(const CharT* s)
{
    return std::ranges::find(s, std::unreachable_sentinel, CharT{}) - s;
}
 
template<class CharT>
constexpr std::size_t find_first(const CharT *haystack, const CharT *needle)
{
    const char* needle_end = needle + strlen(needle);
    // search(begin, unreachable_sentinel) 通常由于每次循环少一次比较而比
    // search(begin, end) 更加高效。
    // 但 "needle" **必须出现于** "haystack" 中,否则此调用为 UB,
    // (这在 constexpr 语境中是编译期错误)。
    auto found = std::ranges::search(haystack, std::unreachable_sentinel,
                                     needle, needle_end);
    return found.begin() - haystack;
}
 
int main()
{
    static_assert(strlen("The quick brown fox jumps over a lazy dog.") == 42);
    static_assert(find_first("unsigned short int", "short") == 9);
//  static_assert(find_first("long int", "float")); // 编译期错误
}

参阅

由通过重复对某个初值自增所生成的序列组成的 view
(类模板) (定制点对象)