subrange_get

subrange_get (subrange 구조적 바인딩 get)

std::ranges::getstd::ranges::subrange에 대한 구조적 바인딩(structured binding) 지원을 제공하는 함수예요. C++20부터 사용할 수 있어요.

출처: cppreference

본문

<ranges> 헤더에 정의되어 있고, 시그니처는 다음과 같아요.

template< std::size_t N, class I, class S, ranges::subrange_kind K >
    requires ((N == 0 && std::copyable<I>) || N == 1)
constexpr auto get( const ranges::subrange<I, S, K>& r );

(1) (since C++20)

template< std::size_t N, class I, class S, ranges::subrange_kind K >
    requires (N < 2)
constexpr auto get( ranges::subrange<I, S, K>&& r );

(2) (since C++20)

namespace std { using ranges::get; }

(3) (since C++20)

구조적 바인딩 지원을 제공해요.

    1. N == 0 또는 N == 1일 때 각각 subrange lvalue(또는 const rvalue)에서 반복자 또는 센티널을 얻어요.
    1. (1)과 같지만, 비-const subrange rvalue를 받아요.
    1. 오버로드 (1,2)가 namespace std로 임포트되어 사용을 단순화하고, 복사 가능한 반복자를 가진 모든 subrange를 pair-like 타입으로 만들어요.

매개변수 (Parameters)

  • r — subrange

반환값 (Return value)

  • 1,2) N이 0이면 r.begin()을 반환해요. 그 외(N이 1)에는 r.end()를 반환해요.

예제 (Example)

이 코드를 실행해 봐요.

#include <array>
#include <iostream>
#include <iterator>
#include <ranges>

int main()
{
    std::array a{1, -2, 3, -4};

    std::ranges::subrange sub_a{std::next(a.begin()), std::prev(a.end())};
    std::cout << *std::ranges::get<0>(sub_a) << ' '   // == *(begin(a) + 1)
              << *std::ranges::get<1>(sub_a) << '\n'; // == *(end(a) - 1)

    *std::get<0>(sub_a) = 42; // OK
//  *std::get<2>(sub_a) = 13; // Error: index can only be 0 or 1
}

더 알아보기 (Learn more)

cppreference