命名空间
变体
操作

std::unreachable_sentinel_t, std::unreachable_sentinel

来自 cppreference.cn
< 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) is usually more efficient than
    // search(begin, end) due to one less comparison per cycle.
    // But "needle" MUST BE PRESENT in the "haystack", otherwise the call
    // is UB (which is a compile-time error in constexpr context).
    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")); // compile-time error
}

[编辑] 参见

一个由重复递增初始值生成的序列组成的 view
(类模板) (定制点对象)[编辑]