iterator_unreachable_sentinel_t
iterator_unreachable_sentinel_t (무한 구간의 상한 센티널)
<iterator> 헤더에 정의되어 있어요. 무한한(끝이 없는) 구간의 "상한"을 나타내는 빈 클래스 타입이에요. 실제로 끝에 도달하는 일이 없는 범위를 다룰 때 유용해요.
출처: cppreference
본문
unreachable_sentinel_t는 빈 클래스 타입으로, 끝이 없는 구간(unbounded interval)의 상한을 나타내는 데 쓰여요.
struct unreachable_sentinel_t; // (1) since C++20
inline constexpr unreachable_sentinel_t unreachable_sentinel{}; // (2) since C++20
-
unreachable_sentinel_t는 무한 구간의 "상한"을 나타낼 수 있는 빈 클래스 타입이에요.
-
unreachable_sentinel은unreachable_sentinel_t타입의 상수예요.
비멤버 함수
unreachable_sentinel_t를 어떤 weakly_incrementable 타입의 값과 비교해요. 결과는 항상 false예요.
template<std::weakly_incrementable I>
friend constexpr bool operator==( unreachable_sentinel_t, const I& ) noexcept
{ return false; }
unreachable_sentinel_t는 어떤 weakly_incrementable 타입과도 비교할 수 있고, 그 결과는 언제나 false예요. 이 함수 템플릿은 일반적인 한정(unqualified)·한정(qualified) 탐색으로는 보이지 않고, 인자 연관 탐색(argument-dependent lookup)에서만 찾을 수 있어요.
예제
#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예요.
auto found = std::ranges::search(haystack, std::unreachable_sentinel,
needle, needle_end);
return found == std::unreachable_sentinel ? -1 : found - haystack;
}
std::ranges::search 같은 알고리즘과 함께 쓰면 널 종료 문자열처럼 끝을 미리 모르는 범위를 안전하게 다룰 수 있어요.