C++ N-Tuple 타입 작성하기

이경헌·2023년 8월 9일
0

컴파일 시간에 정해진 크기 N에 대해 동일한 타입 (이하 T)를 묶어 다루고 싶을 땐 std::array<T, N>을 사용할 수 있습니다.

하지만 만일 T가 레퍼런스 타입인 경우 std::array를 사용할 수 없습니다 (참조).

std::tuple을 사용하면 레퍼런스 타입을 사용할 수 있지만, 템플릿 인자에 TN번 입력해야 합니다. 예를 들어 N이 4일 때, std::tuple<T, T, T, T>와 같이 불편합니다.

편의를 위해 이를 간단히 하는 타입을 정의할 수 있습니다 (std ≥ c++14).

#include <tuple>

template <std::size_t, typename T>
using index_pair = T;

template <typename T, std::size_t N, typename = std::make_index_sequence<N>>
struct n_tuple_base;

template <typename T, std::size_t N, std::size_t... I>
struct n_tuple_base<T, N, std::index_sequence<I...>>{
    using type = std::tuple<index_pair<I, T>...>;
};

template <typename T, std::size_t N>
using n_tuple = n_tuple_base<T, N>::type;

사용례는 다음과 같습니다 (std ≥ c++17).

#include <vector>

int main(){
    // Example 1: n_tuple declaration.

    auto indices = n_tuple<int, 4> { 0, 1, 2, 3 };
    static_assert(std::is_same_v<decltype(indices), std::tuple<int, int, int, int>>);

    // Example 2: can use reference type.

    std::vector ints { 1, 2, 3, 4, 5 };
    auto int_view = n_tuple<int&, 3> { ints[0], ints[1], ints[2] };
    std::get<0>(int_view) = 6; // ints == { 6, 2, 3, 4, 5 }
}

Compiler Explorer에서 확인하기

profile
Undergraduate student in Korea University. Major in electrical engineering and computer science.

1개의 댓글

comment-user-thumbnail
2023년 8월 9일

많은 것을 배웠습니다, 감사합니다.

답글 달기